Setting 'target object' on instantiated prefab.

I have a prefab spawn which creates an object+script. This script needs to alter another script attached to another object.

If I manually place the prefab into the scene and then set the ‘target object’ (which is permanent and static) from the inspector, it works perfectly. However, I can’t set this ‘target object’ for the prefab under the project tab (ie. so that it inherently has this target when it spawns) - is there some way I can automatically set this target when the prefab spawns, or is there some easier method I am missing?

Thanks

You can set it up like this.

var target : transform;

function Start(){
target = GameObject.FindWithTag("YourTag").transform;
}

Thanks for the reply, but I still can’t figure out how to incorporate it into my code. I’m prety new at this, let me try and explain a bit better. Here’s what I have at the moment:

var fallspeed = 1;
var lifeTime = 10;
var target : InkTotal;

function Awake()
{
Destroy (gameObject, lifeTime);
}


function Update() 
{
transform.Translate(0.005*-fallspeed*Time.deltaTime, 0, 0);
}


function OnMouseDown()

{if (target.inkTotal < 10)

{
Destroy (gameObject);
target.inkTotal ++;
target.cartridgeTotal = 0;
Debug.Log (target.cartridgeTotal); 
}}

This^^ is the script running on the spawned object.
InkTotal = the script on target object.
inkTotal cartridgeTotal are variables inside InkTotal.

This works when I manually place the prefab and specify which object(InkCounter) has the ‘InkTotal’ script attached to it, but when the prefab is spawned into existence I get a null reference error, because no object is assigned under the inspector.

How can I tell it where InkTotal is located as soon as it is created?

Thanks

Ok, here is your code with the built in find function. Change "InkCartridge to whatever the name is of the target, and create a function in the InkTotal script to do the stuff I commented out. The reason you’ll have to do the function in the other script is because it kept coming up with a weird error. I’m sure there’s away around that but this is what I could come up with that worked.

var fallspeed = 1; 
var lifeTime = 10;
var target; 

function Awake() 
{ 
Destroy (gameObject, lifeTime); 
} 

function Start(){
target = transform.Find("InkCartridge").GetComponent(InkTotal); 
}


function Update() 
{ 
transform.Translate(0.005*-fallspeed*Time.deltaTime, 0, 0); 
} 


function OnMouseDown() {
if (target.inkTotal < 10) 
{ 
target.GetComponent(InkTotal).YourFunction();
//Execute this code in a function in your other script.
/*Destroy (gameObject); 
target.inkTotal ++; 
target.cartridgeTotal = 0; 
Debug.Log (target.cartridgeTotal);*/
}}
1 Like

Thanks for your help. Turns out I just had to make inkTotal and cartridgeTotal static vars instead of vars ¬_¬