2014年8月28日 星期四

Unity 存取其他 Component 與存取不同 Object 方法

因為這陣子專案正邁向整合階段,固有許多不同Script或不同Object需要互相存取的需求產生,其實在Unity裡,要達成上述並不難,首先我們先釐清一些觀念:Component 是附加在 GameObject上,故Component可以為腳本或一些效果如Renderer,Collider,Animation等,所以同個GameObject可能會有許多Components!然後我們就可以來簡單嘗試一下如何調用囉!



  • 同一物件下,不同Components的互相調用

首先我們先創件兩個Scripts分別為AnotherScript.cs、UsingOtherComponents.cs並 attach 到一個空的GameObject,如下圖:
範例程式碼如下:
using UnityEngine;
using System.Collections;
//AnotherScript.cs
public class AnotherScript : MonoBehaviour {
 public int playerScore = 9001;
}

之後按Play後就可以發現Console裡出現 "The player's score is 9001" 那麼就成功啦!

  • 不同Object,不同Components的互相調用
因為不可能把所有的Components放在同一GameObject裡,所以存取不同物件也是很正常的事情!而實做方法與上面很雷同,只是要用 GameObeject.Find ("ObjectName") 或 GameObject.FindWithTag ("ObjectTag") 去指定要存取的物件即可。

接續上面範例,只是我們再加入另一個空的GameObject並 attach上 YetAnotherScript.cs 且更改其Tag為 GameController (隨便設皆可),這裡只是範例你也可以直接改物件名稱,示範如下:
using UnityEngine;
using System.Collections;
//YetAnotherScript.cs
public class YetAnotherScript : MonoBehaviour {
 public int numberOfPlayerDeaths = 3;
}















之後按Play後就可以發現Console裡出現 "The player's score is 9001","The player's death :3" ,那麼就okay了!

下面是幾個官方的範例與說明:

  1. Unity Learn Documentation - Accessing Other Components
  2. Unity Learn Documentation - Accessing Other Game Objects

沒有留言:

張貼留言