最近做的一個項目,是鼠標點擊左鍵在plane上畫線,其中,界面上有NGUI的button,點擊用來改變線的顏色,顯然主要畫線腳本綁定在攝像頭上面,而button響應(yīng)事件的腳本綁定在對應(yīng)的button上面,不同對象上面綁定的腳本怎么來實現(xiàn)點擊button響應(yīng)呢,下面就來說一說。
首先,要在畫線腳本上寫一個對外接口函數(shù),比如改變顏色的對外接口函數(shù),我這么寫:
<pre><code>
public void set_linecolor() //定義為公有型的函數(shù)
{
linecolor = Color.red; //linecolor是全局變量
line = new VectorLine("DrawnLine", linePoints,linecolor,lineMaterial, lineWidth, LineType.Continuous);
}
</code></pre>
對應(yīng)的在button上面綁定一個腳本,里面要找到MainCamera對象,再找到這個對象上面的腳本,我這里是test,然后,再調(diào)用腳本里面改變顏色的對外接口函數(shù)set_linecolor,這樣就實現(xiàn)響應(yīng)機制了。
button上面腳本:
<pre><code>
using UnityEngine;
using System.Collections;
public class bb1 : MonoBehaviour {
//定義一個對象標簽
private GameObject myobj1;
// Use this for initialization
void Start () {
//獲得標簽對象
myobj1 = GameObject.FindWithTag("MainCamera");
}
// Update is called once per frame
void Update () {
}
//button響應(yīng)事件
void OnClick()
{
test t = GetComponent<test>();//找到腳本test
t.set_linecolor();//調(diào)用腳本里面的函數(shù)
Debug.Log("button!"); //測試是否響應(yīng)
}
}
</code></pre>
這樣就可以實現(xiàn)點擊button,改變顏色了。(當然還要將test腳本拖拽到button上面,然后添加相應(yīng)的畫線材質(zhì),碰撞體,這樣才能實現(xiàn),不然會錯誤提示找不到對象,這個很重要!?。?br>
但是這樣其實還有一個缺陷,就是,當需要改變的顏色很多的時候,那是不是要定義很多個對外接口函數(shù)?所以這樣也不方便,但有一個解決方法很好,就是利用參數(shù)傳遞的方法。
下面是改變寬度的對外接口函數(shù):
<pre><code>
//公有類型函數(shù),里面有一個float型參數(shù),用來傳遞寬度
ublic void set_linewidth(float line_width)
{
lineWidth = line_width; //將傳遞的寬度賦值給畫線的寬度
line = new VectorLine("DrawnLine", linePoints,linecolor,lineMaterial, lineWidth, LineType.Continuous);
}
</code></pre>
然后在,button里面建立腳本,調(diào)用:
<pre><code>
using UnityEngine;
using System.Collections;
public class bb1 : MonoBehaviour {
//定義一個對象標簽
private GameObject myobj1;
// Use this for initialization
void Start () {
//獲得標簽對象
myobj1 = GameObject.FindWithTag("MainCamera");
}
// Update is called once per frame
void Update () {
}
//button響應(yīng)事件
void OnClick()
{
test t = GetComponent<test>();//找到腳本test
t.set_linewidth(4.0f);//調(diào)用腳本里面的函數(shù),并傳遞一個float型的參數(shù)
Debug.Log("button!"); //測試是否響應(yīng)
}
}
</code></pre>
這樣的話,畫線腳本里面只要創(chuàng)建一個對外接口函數(shù)即可以,只是不同button的時候傳遞不同參數(shù)便可以了,這樣可能方便多了,讓我想到c++里面的代碼重用_(當然還要重復(fù)操作將test拖到button上面,再拖拽畫線材質(zhì),碰撞體才能實現(xiàn))。