Set a variable from another script
I know this question has been asked to death, however I see so many different answers and I haven't been able to make any of them work for me. Which way is the best one?
I haven't been albe to make any of them work for me. Which way is the best one?
:) what didn't work? What was the problem. I don't see a point in explaining the best way if you can't make it work anyways.
There is basically only one way to set a variable on another script. Get a reference to the script (instance) that has the variable and set it using that reference.
Yeah there's a few ways of doing this and the best way is the one you understand and the one that works.
Answer by Mmmpies · Jun 11, 2016 at 10:20 AM
Best or easiest?
The easiest way is to reference the name of the other script in a public variable and have the variable that you want to set public as well. Let's say you have a ChangeMe.cs script and an ApplyChange.cs script (the names aren't important I'm just using them for ease of explanation).
In ChangeMe you have a bool.
public bool AmIChanged = false;
In ApplyChange you reference the script ChangeMe in a public variable.
public ChangeMe myChangeMeScript;
void Start()
{
myChangeMeScript.AmIChanged = true;
}
Drag both scripts onto a GameObject (just a cube it's not important but they need to be in scene). Drag the cube onto the public slot for the myChangeMeScript script.
Look at the value of the bool and it should be false. Click play and it should turn to true.
You can also use getters and setters for private variables but get used to how you reference a script from another first then try one of the many tutorials that mention these.
Do they need to be in the same GameObject? What is they are in different GameObjects? I tried this but didn't work. http://pastebin.com/WXqqBGqv
No that public variable is the key, whatever object the script is on that shows that public slot in the inspector just needs whatever object the other script is on dragging onto that slot.
Is your script trying to interact with a Button on a Canvas?
If so then you also need
using UnityEngine.UI;
at the top of the script.
Thanks, finally it works. So, if this is the easiest, what is the best one then, if you don't $$anonymous$$d answering?
Your answer
Follow this Question
Related Questions
How to access non static C# variable from another C# script 1 Answer
C# - Cannnot access variable in another script unless I get the component everytime. 1 Answer
Custom inspector. Pick one bool from a list. 1 Answer
Interchangeable animations in a script? 0 Answers
Change in Editor via Script Values of another Script 2 Answers