您的位置:首页 > 移动开发 > Unity3D

unity之GameObject

2015-09-06 18:46 447 查看
1.设置物体的tag

this.gameObject.tag = "Player";


2.设置物体是够活跃

//效果一样的
//   this.gameObject.active = false;
//   this.gameObject.SetActive(false);
//设置游戏物体及子物体的活跃状态
this.gameObject.SetActiveRecursively(false);

3.在脚本中画基本GameObject

GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);

4.调用同级脚本的方法,采用你要调用的那个对象.SendMessage方法
比如:有2个Cube,我在Cube1中调用Cube2的一个方法,只需在Cube1中获取到Cube2对象,然后用Cube2.SendMessage(string Method,Method方法的参数);

本质也就是,用该类的对象调用该类的方法(类似于方法调用)

例:我在Cube2中调用Cube2中的Print方法

</pre><pre name="code" class="csharp">public class cube2 : MonoBehaviour
{

void Update ()
{
if(Input.GetKeyDown(KeyCode.K))
{
this.gameObject.SendMessage("Print", "2被点了,快跑");
}
}

void Print(string str)
{
print(str);
}
}

例:我在Cube1中调用Cube2的Print方法
public class cube1 : MonoBehaviour 
{
   private GameObject cube2;
<span style="white-space:pre"> </span>void Start () 
    {
      cube2 = GameObject.Find("Cube2");
<span style="white-space:pre"> </span>}

<span style="white-space:pre"> </span>void Update () {

       if(Input.GetKeyDown(KeyCode.C))
       {
         cube2.SendMessage("Print","在cube1中调用cube2的Print方法");
        }
<span style="white-space:pre"> </span>}

  void Print2(string str) {
        print(str);
    
    }
}5.孩子想调用父亲里的方法怎么办呢?使用SendMessageUpwards方法
例如,我的Cube1还有一个Sphere孩子,已知Cube1中有一个Print2方法

在Sphere中想要调用它爸爸中的Print2方法

public class sphere1 : MonoBehaviour 
{

<span style="white-space:pre"> </span>void Update () 
    {
<span style="white-space:pre"> </span>if(Input.GetKeyDown(KeyCode.U))
    {

        this.transform.parent.SendMessageUpwards("Print2","球被点了。爸爸");
    }

}
}6.在爸爸中想要调用孩子里的方法怎么办呢,使用BroadcastMessage方法
在Sphere中添加一个方法

void Son(string son) {
print(son);
}我们就想在cube1中调用Sphere中的这个方法
if (Input.GetKeyDown(KeyCode.L))
{

this.gameObject.BroadcastMessage("Son", "爸爸发送消息");
}当一个父亲有好几个孩子,这好几个孩子同时调用父亲中的这个方法呢?
CubeFather中

public class CubeFather : MonoBehaviour
{
int a = 0;

void Update ()
{
Debug.Log("父亲自己的a=="+a);
}

void Add(int n)
{
a = a + n;
Debug.Log(a+"");

}

}Son1中
public class Son1 : MonoBehaviour
{
void Update ()
{
this.gameObject.SendMessageUpwards("Add",1);
}
}Son2中
public class Son2 : MonoBehaviour
{
void Update ()
{
this.gameObject.SendMessageUpwards("Add",2);
}

}
结果:从这可以看出,是先调用Son2中方法,然后调用Son1中的方法,最后调用Father中的Update方法

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  GameObject unity