Multiple Copies of Prefab, Unique Names?

I have to questions.

First I want to create multiple copies of lets just say a crate. What I’m wondering is if it’s possible when these are created to assign a variable or a name to each that would be unique. Something simple like a number.

The goal is so that when the player triggers one of these crates, the number can be pulled off the crate and it’s state checked and the appropriate action taken.

So my question is this. How do I go about creating multiple copies of a prefab and assigning a unique variable name.

Then is it possible to make a call to that variable from another script?

I’m currently using Javascript to do this.

Thanks!

Could you have a Crate object with an ID variable added to your crate prefab.

Then have an InitializeCrates object with an InitializeCrates script. Add an awake method to the class then loop through all the crate objects using FindObjectsOfType.

You could do it in one script I guess by having a static boolean to check if you had already run the awake method.

Are these crates created at runtime (via code), or do they exist in the scene before you hit play?

Yes they’ll be created via a script at the beginning of each level. I had a similar idea to yours Richey after I made the post.

My only other question is this. After assigning variables to each create, is it possible to check the current states of variables within scripts attach directly to that crate?

Like if I have 3 crates. Collide with #2, check it’s move state variable and apply the appropriate logic.

The OnCollisionEnter is passed a collision object of the object being collided with.

So you could do something like (in c# i’m afraid)

void OnCollisionEnter(Collision c)

Create crate = c.gameObject.GetComponent(typeof(Crate)) as Crate;

if (crate!=null) //Check there is a create
{
// crate.ID should be the variable your after.
}

Thanks! I’m actually just starting out with Unity. I’ve done both C# and Javascript. Only reason I used Javascript was because the examples were mostly done in that.

I’ll give that a try!

Thanks!

I did achieve the same effect with Javascript as the example that you gave Richey. I’ll post it for an future references to this post.

var moving = true;
function Update () 
{
	if(moving)
	{
		transform.Translate(-10*Time.deltaTime,0,0);
	}
}

function OnTriggerEnter(other : Collider)
{
	if(other.gameObject.CompareTag("Respawn"))
	{
		moving = false;
		
		var crate = other.gameObject.GetComponent("NewBehaviourScript 1");
		
		
		print(crate.Moving);
	}

	

}

This is on one of the objects. This object has a collider, rigidbody with only IsKinematic turned on.

The other script is simply an update function containing a public variable named Moving.