I’ve been tinkering with my code and was able to bring in variables from script1 on object1 into script2 on object2, i also managed to update the variables on script1, but if i put script1 and script2 on object1, im not able to update the variables in script1. I don’t get any errors (red or yellow) in the console. I added debug.log to the editnumber/bool functions, and i can get numberRef and boolRef to update once, but not more than that. Any help on his issue would be appreciated, and let me know if i should provide more info.
//Script1
//so far script1 just makes these variables
public int obj1number = 10;
public bool obj1bool = false;
//Script2
public GameObject obj1;
private Script1 refScript;
private int numberRef;
private bool boolRef;
void Start()
{
InitializeVariables();
}
void InitializeVariables()
{
refScript = obj1.GetComponent<Script1>();
numberRef = refScript.obj1number;
boolRef = refScript.obj1bool;
Debug.Log(numberRef);
Debug.Log(boolRef);
}
void Update()
{
EditNumber();
EditBool();
refScript.obj1number = numberRef;
refScript.obj1bool = boolRef;
}
//EditNumber and EditBool are basically the same, input changes variable
void EditNumber()
{
if(Input.GetKeyDown(KeyCode))
{
numberRef +=1;
}
You need to specify a KeyCode, such as “KeyCode.Space”, otherwise what key press is it looking for?
Also, if the two scripts are on the same GameObject, you don’t need a reference to that GameObject. You can just call GetComponent() and it defaults to the same GameObject that the script is running on. Otherwise the way you have it setup is you need to set the reference to obj1 in the inspector manually. If you didn’t though then you would be hitting a null reference error when you hit play, so I’m assuming you’ve set that correctly.
I’d add a small suggestion: update your number and bool if they are modified. If the keycode value is matched, do the update then and there, and remove the assignment that happens every update.
Hopefully some of the previous answers help you get it sorted.
Thank you for the responses,
i didn’t copy the code verbatim, so it i messed up a little with the keycode line, it was supposed to be KeyCode.LeftShift; obj1 is public, so i dragged the gameobject to the script in the inspector, and thanks for that last bit, i dont think i planned on keeping the assignment in the update function, i have notes for updating the origin variable with its own function, but it could be simpler to update it with the key press. I’ll try out the changes when i get home from work.