unity 如何腳本間交互


  1. 如何腳本間交互:

   方法1:

   通過在編輯器里面拖動,來持有這個對象去調用對應的函數,這個方法比較簡單。

   在編輯器中新建2個腳本。

   

我們寫一個a腳本

public class Ascript : MonoBehaviour {

// Use this for initialization

void Start () {

 

}

// Update is called once per frame

void Update () {

 

}

public void DoSomething()

{

Debug.LogWarning ("Ascript .. DoSomething .. Call");

}

}

我們想Main腳本去調用A腳本。我們就在Main 寫一個A對象。

         public Ascript ascript_;

這個是在代碼編寫的時候已經可以調用A對象的public 函數。

if (ascript_)

ascript_.DoSomething ();

但其實這個ascript_ 對象是空的,我們要對它賦值。這個時候我們在編輯器拖一個有a腳本的實體對象上去就可以了。

 

我們看見Debug.LogWarning ("Ascript .. DoSomething .. Call");有執行。

 

方法2

我們把上面的直接調用改成 

     if (ascript_)

ascript_.SendMessage ("DoSomething");

我們把a腳本里面的DoSomething函數的public 去掉。

我們看見Debug.LogWarning ("Ascript .. DoSomething .. Call");有執行。

我們嘗試給函數加一些參數,看看結果。

我們對A腳本的 DoSomething 進行修改。

void DoSomething(int param1)

{

Debug.LogWarning (string.Format("{0} {1}","Ascript .. DoSomething .. Call",param1));

}

如果我們腳本中有2個同名的函數會怎么樣呢。

測試結果是誰在上面誰就會被調用。

可以在后面加一個參數。

RequireReceiver

A receiver is required for SendMessage.

if (ascript_) ascript_.SendMessage("DoSomething",2,SendMessageOptions.RequireReceiver);

我們把 a腳本的 DoSomething 函數刪掉。

結果報錯了

 

我們把參數換了試試。

if (ascript_) ascript_.SendMessage("DoSomething",2,SendMessageOptions.DontRequireReceiver);

我們發現不報錯了。

 

  1. Public static

我們a腳本的DoSomething函數改成

public static void DoSomething()

{

Debug.LogWarning(string.Format("{0} {1}","Ascript .. DoSomething .. Call","static function"));

}

我們直接 Ascript.DoSomething ();調用就可以了。

我們再在這個基礎上面改成下面這個樣子。

public class Ascript : MonoBehaviour {

 

public static Ascript aStatic;

// Use this for initialization

void Start () {

aStatic = this;

}

 

// Update is called once per frame

void Update () {

 

}

public void DoSomething()

{

Debug.LogWarning(string.Format("{0} {1}","Ascript .. DoSomething .. Call","static Object"));

}

}

我們把調用的改成,Ascript.aStatic.DoSomething ();

我們這個時候已經不持有這個對象了。

但是場景一定要這個對象,如果沒有的話會報下面的錯。

 

如果我們場景里面有很多這個對象,他會找到這個對象最早生成的那個,注意不是你創建的實體對象而是第一個拖上這個腳本的對象。

 

  1. 如何腳本間交互:

   方法1:

   通過在編輯器里面拖動,來持有這個對象去調用對應的函數,這個方法比較簡單。

   在編輯器中新建2個腳本。

   

我們寫一個a腳本

public class Ascript : MonoBehaviour {

// Use this for initialization

void Start () {

 

}

// Update is called once per frame

void Update () {

 

}

public void DoSomething()

{

Debug.LogWarning ("Ascript .. DoSomething .. Call");

}

}

我們想Main腳本去調用A腳本。我們就在Main 寫一個A對象。

         public Ascript ascript_;

這個是在代碼編寫的時候已經可以調用A對象的public 函數。

if (ascript_)

ascript_.DoSomething ();

但其實這個ascript_ 對象是空的,我們要對它賦值。這個時候我們在編輯器拖一個有a腳本的實體對象上去就可以了。

 

我們看見Debug.LogWarning ("Ascript .. DoSomething .. Call");有執行。

 

方法2

我們把上面的直接調用改成 

     if (ascript_)

ascript_.SendMessage ("DoSomething");

我們把a腳本里面的DoSomething函數的public 去掉。

我們看見Debug.LogWarning ("Ascript .. DoSomething .. Call");有執行。

我們嘗試給函數加一些參數,看看結果。

我們對A腳本的 DoSomething 進行修改。

void DoSomething(int param1)

{

Debug.LogWarning (string.Format("{0} {1}","Ascript .. DoSomething .. Call",param1));

}

如果我們腳本中有2個同名的函數會怎么樣呢。

測試結果是誰在上面誰就會被調用。

可以在后面加一個參數。

RequireReceiver

A receiver is required for SendMessage.

if (ascript_) ascript_.SendMessage("DoSomething",2,SendMessageOptions.RequireReceiver);

我們把 a腳本的 DoSomething 函數刪掉。

結果報錯了

 

我們把參數換了試試。

if (ascript_) ascript_.SendMessage("DoSomething",2,SendMessageOptions.DontRequireReceiver);

我們發現不報錯了。

 

  1. Public static

我們a腳本的DoSomething函數改成

public static void DoSomething()

{

Debug.LogWarning(string.Format("{0} {1}","Ascript .. DoSomething .. Call","static function"));

}

我們直接 Ascript.DoSomething ();調用就可以了。

我們再在這個基礎上面改成下面這個樣子。

public class Ascript : MonoBehaviour {

 

public static Ascript aStatic;

// Use this for initialization

void Start () {

aStatic = this;

}

 

// Update is called once per frame

void Update () {

 

}

public void DoSomething()

{

Debug.LogWarning(string.Format("{0} {1}","Ascript .. DoSomething .. Call","static Object"));

}

}

我們把調用的改成,Ascript.aStatic.DoSomething ();

我們這個時候已經不持有這個對象了。

但是場景一定要這個對象,如果沒有的話會報下面的錯。

 

如果我們場景里面有很多這個對象,他會找到這個對象最早生成的那個,注意不是你創建的實體對象而是第一個拖上這個腳本的對象。

 

  1. 單例模式

    我們參考http://wiki.unity3d.com/index.php/Singleton

 

public class MyClass : MonoBehaviour { void Awake () { Debug.Log(Manager.Instance.myGlobalVar); } }
public class Manager : Singleton<Manager> { protected Manager () {} // guarantee this will be always a singleton only - can't use the constructor!   public string myGlobalVar = "whatever"; }

using UnityEngine;

/// <summary>
/// Be aware this will not prevent a non singleton constructor
/// such as `T myT = new T();`
/// To prevent that, add `protected T () {}` to your singleton class.
///
/// As a note, this is made as MonoBehaviour because we need Coroutines.
/// </summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;

private static object _lock = new object();

public static T Instance
{
get
{
if (applicationIsQuitting) {
Debug.LogWarning("[Singleton] Instance '"+ typeof(T) +
"' already destroyed on application quit." +
" Won't create again - returning null.");
return null;
}

lock(_lock)
{
if (_instance == null)
{
_instance = (T) FindObjectOfType(typeof(T));

if ( FindObjectsOfType(typeof(T)).Length > 1 )
{
Debug.LogError("[Singleton] Something went really wrong " +
" - there should never be more than 1 singleton!" +
" Reopening the scene might fix it.");
return _instance;
}

if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(singleton) "+ typeof(T).ToString();

DontDestroyOnLoad(singleton);

Debug.Log("[Singleton] An instance of " + typeof(T) +
" is needed in the scene, so '" + singleton +
"' was created with DontDestroyOnLoad.");
} else {
Debug.Log("[Singleton] Using instance already created: " +
_instance.gameObject.name);
}
}

return _instance;
}
}
}

private static bool applicationIsQuitting = false;
/// <summary>
/// When Unity quits, it destroys objects in a random order.
/// In principle, a Singleton is only destroyed when application quits.
/// If any script calls Instance after it have been destroyed,
/// it will create a buggy ghost object that will stay on the Editor scene
/// even after stopping playing the Application. Really bad!
/// So, this was made to be sure we're not creating that buggy ghost object.
/// </summary>
public void OnDestroy () {
applicationIsQuitting = true;
}
}

 

 

 

 

 

 

   

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM