- Home /
How to change script's value for only one object?
I have a lot of objects and they all use one the same script. I want to change script's value for only one object. How can I do it?
Doesn't work:
Component obj;
void Start ()
{
obj = gameObject.GetComponent<WaypointAI>();
}
void OnTriggerEnter()
{
obj.patrolSpeed = 5;
}
Work, but change value for all objects, which use script, not for one:
MyScriptName obj;
void Start ()
{
obj = gameObject.GetComponent<ComponentWhichContainScript>();
}
void OnTriggerEnter()
{
obj.patrolSpeed = 5;
}
Is patrolSpeed declared as static? That would explain the value changing for all instances of the script. Otherwise, because you are just getting a single component the change should only apply to a single instance, which in this case should be the script on the same game object as the calling script.
Answer by termway · Mar 23, 2015 at 05:32 PM
I'm not sure of what you call script and object (GameObject and Component?) But if you have the same component on several gameobject you can add a public field to your component and then change the value of your object from the Inspector.
public int speed = 5;
//...
void OnTriggerEnter()
{
obj.patrolSpeed = speed;
}
Update :
Check if your special component exist/ is present and change the value if required.
bool isSpecial;
void Start ()
{
obj = gameObject.GetComponent<ComponentWhichContainScript>
isSpecial = (obj != null);
//or something like this isSpecial = obj.IsSpecial();
}
void OnTriggerEnter()
{
obj.patrolSpeed = (isSpecial)? 4 : 5;
}
But I need to change it automatically, not by hands
Answer by JigneshKoradiya · Mar 23, 2015 at 08:06 PM
give tag to that gameobject when it collide and check the gameobject which has tag and you script and change value of that gameobject script
Your answer
Follow this Question
Related Questions
Convert Script To String - Not your average typecasting 2 Answers
Make an object a certain distance from me. 2 Answers
C# script who draw a line in EditMode 0 Answers
my prefab clone object are falling from ground in y direction? 0 Answers
Error in code 1 Answer