- Home /
Change property value of prefab instance
Hi,
This is a beginners question:
I have a prefab with a script named OnClickAction containing a field (Hitpoints field).
public int HitPoints;
In this scripts Update function I sometimes update the HitPoints.
I clone this prefab programmaticaly in another script named Generator (in an array).
GameObject go = (GameObject)Instantiate(prefab, new Vector3(xIndex, yIndex, zIndex), new Quaternion(1f,1f,1f,1f)) as GameObject;
My goal is to increment the value of HitPoints of an instance of a prefab when its clicked (the code for this is in OnClickAction in the Update)
if (Input.GetButton("Fire1"))
{
//Hit, update hit points.
HitPoints++;
Debug.Log(HitPoints);
}
but what happens is that the HitPoints on all clones increments (and not on a specific prefab instance).
How can I fix this behavior. There is no "static" definintion of the HitPoints field.
Thanks.
Answer by -hiTo- · Aug 24, 2013 at 04:18 PM
The script is there on all clones, so the if-statement will be run on all clones. Hence, all of your clones will run the code within.
What you probably want is to use the function OnMouseDown.
This will only run when you click an object's collider.
private void OnMouseDown()
{
HitPoints++;
}
Your answer
Follow this Question
Related Questions
How do I instantiate a prefab B in same place prefab A? 1 Answer
Affect All Instances Of A Prefab 3 Answers
How to remove a specific instance of a prefab from List? 1 Answer
Gameobject missing camera when instance prefab 3 Answers
How can I set the material on an instance after creating it? 1 Answer