talking to scripts from instantiated objects?

Hi,

I’m having trouble communicating between objects.

Can anyone explain why this is not working:

// Set up a link to the prefab (from the inspector)
var myPrefab : Transform;

function Start () {

	for (var i=0;i<10;i++) {
		myPrefab = Instantiate (myPrefab, Vector3(i*1, 0, 0), Quaternion.identity);
		myPrefab.name = "Prefab"+i;
	}
	
	var currentObject = GameObject.Find("Prefab3");
	
	// This works:
	currentObject.transform.position.y += 2;
	
	// This doesn't work:
	currentObject.GetComponent(Slave).DoSomething();
	
}

The Prefab ‘myPrefab’ has a script attached to it called ‘Slave’ as follows:

function DoSomething() {
	transform.renderer.material.color = Color.blue;		
}

The error message I get is:

"‘DoSomething’ is not a member of ‘UnityEngine.Component’. "

? thanks for any help!
[/code]

For one, in your for loop, have a temproary variable. Using myPrefab for both the base for instantiation and the temporary storage you can manipulate, otherwise changes you make will accumulate, and the original variable will no longer be valid after the loop is run.

Second,

   currentObject.GetComponent(Slave).DoSomething();

GetComponent returns a Component, which (as the error suggests) doesn’t know what DoSomething is. Typecast it to a type that does:

   var slave : Slave = currentObject.GetComponent(Slave);
slave.DoSomething();

StarManta - thank you so much for your speed reply, it is very appreciated this end!

I understand the second bit now - and it works perfectly, thanks - (learning all the time!).

I think the examples here <file:///Applications/Unity%20iPhone/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html> are a bit confusing in this respect.

I’m not sure I quite understand what you mean about the for-loop and the temporary variable though?

Do you mean, I should do this:

for (var i=0;i<10;i++) {
		var temp = Instantiate (myPrefab, Vector3(i*1, 0, 0), Quaternion.identity);
		temp.name = "Prefab"+i;
	}

?

Thanks again - IOU a 1x beer.