- Home /
Edit variable in script B from script A
Lets say I have two scripts. ScriptA and ScriptB. I'd like one of my variables in ScriptB to be influenced by a variable in ScriptA, this seems pretty simple, but it is not working out so well for me. Also I'd like to note that there may be many objects with ScriptA and ScriptB in them as a component.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptA : MonoBehaviour {
public int MyFavoriteNumber;
void Start () {
MyFavoriteNumber = 11;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptB : MonoBehaviour {
public GameObject ObjectWithScriptBInIt;
public int MyFavoriteNumberTimesTwo;
private NameScript VarScriptA;
void update () {
VarScriptA = ObjectWithScriptBInIt.GetComponent<ScriptA> ();
MyFavoriteNumberTimesTwo = VarScriptA.MyFavoriteNumber;
}
}
You should be able to make VarScriptA public, use the correct type (ScriptA), and just assign it in the inspector.
public class ScriptB : $$anonymous$$onoBehaviour {
public int $$anonymous$$yFavoriteNumberTimesTwo;
public ScriptA VarScriptA;
void update () {
$$anonymous$$yFavoriteNumberTimesTwo = VarScriptA.$$anonymous$$yFavoriteNumber;
}
}
Answer by Bunny83 · Oct 10, 2017 at 05:05 AM
Your Update method starts with a lowercase letter. So it's not called by Unity. Update need to start with en upper case letter.
Also like bobisgod234 mentioned you can simply declare a variable of the type of your other script and directly assign the script instance. That way you don't need to use GetComponent all the time.
So let's say I wanted to access the variable "$$anonymous$$yFavoriteNumber" in the ScriptB script from the ScriptA script, Would I simply say "VarScriptA.$$anonymous$$yFavoriteNumber = 12;"?
So once I have my script variable, how do I go about editing a variable inside my script variable? I thought it was something like "Script.Variable = 79;"??