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窗口中看到打印信息。
Unity 3d C#脚本(1)_第1张图片

用Components控制GameObjects

用GetComponent函数获取组件对象

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

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

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

    // 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");
}

你可能感兴趣的:(unity)