- Home /
Change value of another script to affect multiple objects
Hello everyone. This is probably a very common question but I'm struggling to find a correct and functional answer. So I have 2 scripts ( let's call them script Value and Multiplier for the sake of it) what I'm trying to do is use the Multiplier script to access one variable (float) of the Value script and change that value. The thing is that the Value script is connected with multiple objects (10+). What I want is just to make a reference to the variable and multiply it's value but I'm confused about what's the best approuch. I know I should probably create an array but not sure if would be of GameObjects or Value scripts array... Can someone give me some help?
Answer by fernandoss25 · May 04 at 09:17 AM
It seems I can only use the GetComponent with GameObject. Int or float don't have that it seems. I did tried with game object but still gives me a null reference.
I did found a solution that works:
foreach(var x in FindObjectsOfType<Value>())
{
x.variable = value ;
}
Answer by zjebali · May 03 at 06:22 PM
Your question is worded a bit weird so I'm confused on how to answer it correctly but I'll try.
So you can you create an Array of either GameObjects with the Value script on them or an Array of Value scripts.
Once you have the reference to script or the object make sure the value is public and you should be able to change it in the Multiplier script.
public class Multiplier : MonoBehaviour
{
public int multiplier = 2;
//You would have to populate this array in the editor.
[SerializeField]
private GameObject[] valueGO;
//Call this when you want to change the values
void ChangeValue()
{
foreach(int val in valueGO)
{
val.GetComponent<Value>().valueToChange * multiplier;
}
}
}
public class Value : MonoBehaviour
{
public int valueToChange = 10;
}
I'm not sure if this answers your question.