如何控制预制件的多个实例之一?

时间:2015-07-20 17:01:33

标签: unity3d multiple-instances

我的游戏"读取文件XML,识别一些元素并在运行时对其进行实例化。这个实例是预制件。 所以,我有一个带变量的循环" ins"创建实例:



ins = (GameObject)Instantiate (this.MyPrefab, position, Quaternion.identity);



 例如,我希望单击一个实例并更改其颜色而不是所有实例。

3 个答案:

答案 0 :(得分:1)

代码中的问题是Update()在每个框架中调用Click()。因此,无论何时按下鼠标按钮if( Input.GetMouseButtonDown(0) )对于每个预制件都成立,他们都会处理点击事件,无论是否点击它们。

解决方案是将Collider组件添加到预制件中,并在ButtonDiagram类中实现OnMouseDown()以检测对象上的鼠标点击。类似的东西:

public class ButtonDiagram : MonoBehaviour
{
    // rest of your code

    void OnMouseDown()
    {
        Debug.Log("Click!");
    }
}

Unity的文档: http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html

答案 1 :(得分:0)

你可以做一系列游戏对象。

执行foreach循环并将每个实例添加到数组中。然后你可以做ins [0] .DOSOMETHING,或者更简单,让你实例化的预制件上有一个脚本,然后接受鼠标点击或其他输入,这将只影响用户与之交互的游戏对象/预制件。

答案 2 :(得分:0)



using UnityEngine;
using System.Collections;

public class Program : MonoBehaviour
{

	private Diagram diagram { get; set; }
	public string arquivoXMI;
	public GameObject ButtonDiagramGameObject;
	private const int SPACEX = 2;
	private GameObject ins;
	public ArrayList instances{ get; private set; }

	// Use this for initialization
	void Start ()
	{
		this.diagram = new Diagram (arquivoXMI);

		ButtonForEachSequenceDiagram ();
	}


	//BUTTON FOR EACH SEQUENCE DIAGRAM
	private void ButtonForEachSequenceDiagram()
	{
		instances = new ArrayList ();

		if (this.diagram.SequenceDiagrams.Count > 0) {
			float increment = (this.ButtonDiagramGameObject.transform.localScale.x / 2) + SPACEX;
			float position = 0;

			foreach( Sequence s in this.diagram.SequenceDiagrams )
			{
				float posBDx = position;
				float posBDy = this.ButtonDiagramGameObject.transform.position.y;
				float posBDz = this.ButtonDiagramGameObject.transform.position.z;

				Vector3 posButtonDiagram = new Vector3 (posBDx, posBDy, posBDz);
				ins = (GameObject)Instantiate (this.ButtonDiagramGameObject, posButtonDiagram, Quaternion.identity) ;
				ins.GetComponentInChildren<ButtonDiagram> ().NameDiagram ( s.Name );

				instances.Add(ins);

				position += increment;
			}
		}
	}
	

	// Update is called once per frame
	void Update ()
	{
		foreach( GameObject i in instances ){
			i.GetComponentInChildren<ButtonDiagram>().Click();
		}
	}
	
}





using UnityEngine;
using System.Collections;

public class ButtonDiagram : MonoBehaviour {

	public TextMesh Name;
	public GameObject MyCube;
	private string nameDiagram;
	private float random;

	// Use this for initialization
	void Start () {
//		random = Random.Range(-10.0f, 10.0f);
//		NameDiagram = random.ToString();
		Name.text = nameDiagram;

	}


	public void NameDiagram( string nome ){
		this.nameDiagram = nome;
	}


	public void Click(){
		if( Input.GetMouseButtonDown(0) )
		{
			Debug.Log("Click!");
		}
	}


	// Update is called once per frame
	void Update () {

	}
}
&#13;
&#13;
&#13;