Unity 3d C#脚本(1)

创建和使用脚本

创建C#脚本Assets > Create > C# Script

初始内容

using UnityEngine;
using System.Collections;

public class MainPlayer : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }
}

要使脚本运行,需要将脚本附加到游戏对象(GameObject)上。可以通过将脚本拖拽到hierarchy视图的特定对象上进行绑定,之后在Inspector视图上会出现新添加的脚本的组件。

测试:
在Start中 添加代码

// Use this for initialization
void Start () {
// Debug.Log is a simple command that just prints a message to Unity’s console output
    Debug.Log("I am alive!");
}

点击运行,会在 console窗口中看到打印信息。

这里写图片描述

变量和Inspector

在脚本中可以设置变量,使可编辑变量出现在inspector视图中。将变量设置为public才能在Inspector视图中显示可编辑变量。

using UnityEngine;
using System.Collections;

public class MainPlayer : MonoBehaviour {
    public string myName;

    // Use this for initialization
    void Start () {
        Debug.Log("I am alive and my name is " + myName);
    }

    // Update is called once per frame
    void Update () {

    }
}

代码会在Inspector视图当前组件中创建一个名为”My Name”的可编辑域。
编辑”My Name”之后点击运行,会在console窗口中看到打印信息。
这里写图片描述

用Components控制GameObjects

用GetComponent函数获取组件对象

void Start () {
    Rigidbody rb = GetComponent<Rigidbody>();
}

一旦获取了组件对象,就可以改变其变量。

void Start () {
    Rigidbody rb = GetComponent<Rigidbody>();

    // Change the mass of the object's Rigidbody.
    rb.mass = 10f;
}

访问其它GameObject

public class Enemy : MonoBehaviour {
    public GameObject player;

    void Start() {
        // Start the enemy ten units behind the player character.
        transform.position = player.transform.position - Vector3.forward * 10f;
    }
}

用如上方式,可以通过从Hierarchy面板向 Inspector中拖拽目标的方式给变量赋值。

用GameObject.Find可以通过名字查找特定GameObject

GameObject player;

void Start() {
    player = GameObject.Find("MainHeroCharacter");
}

还可以通过GameObject.FindWithTag、FindGameObjectsWithTag获取特定tag的一个或一组GameObject。

GameObject player;
GameObject[] enemies;

void Start() {
    player = GameObject.FindWithTag("Player");
    enemies = GameObject.FindGameObjectsWithTag("Enemy");
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值