- Home /
Change a value of a script from other script
Hi, i have a question, how can i access to a property of a script and change it.
For example:
I have a script called Enabled that disable Rotate Script, and it works, but how can i acces to Speed property and change it trought another script? lets supouse one called Speed that change value of speed Thanks
Very common question. Google: "Change a value of a script from other script Unity3d"
Answer by mattmanj17 · Oct 21, 2013 at 06:40 PM
see Accessing variables in other script Components
on this page http://docs.unity3d.com/412/Documentation/Manual/Scripting.html
also, you could have found this by putting the title of your question into Google, like robertbu said.
Now your answer is a dead end, because the link you posted leads nowhere. So Im here in 2021 looking for an answer to this question and the trail is dead because you haven't answered it.
wow, this is a blast from the past. It sucks that the link broke. This answer on another question seems to be helpful. http://answers.unity.com/answers/42845/view.html
in the interest of making this a bit more future proof, here is a snip of one of the more brief answers on that question.
if you have a script on an object named 'ThePlayer' that looks like this.
public class PlayerScript: $$anonymous$$onoBehaviour
{
public float Health = 100.0f;
}
then you can fiddle with Health from another script like this
public class Accessor : $$anonymous$$onoBehaviour
{
void Start()
{
GameObject thePlayer = GameObject.Find("ThePlayer");
PlayerScript playerScript = thePlayer.GetComponent<PlayerScript>();
playerScript.Health -= 10.0f;
}
}
I wish you luck using unity in 2021. Sorry if me from 7 years ago made your day a little worse.
I owe an apology. I did not mean to come across as snappy, I had just gotten frustrated because I had found many answers like this that linked to a broken web page.
I would like to ask about this however.
PlayerScript playerScript = thePlayer.GetComponent<PlayerScript>();
the above line will create an instance of the class 'PlayerScript' right? So It will essentially run the Start() method again and will not have the variable values that have been changed over time of the game running. Its not the same instance of the script I had when I first ran the game.
I wish to call a method that returns which wave number I am on. for relational sakes: PlayerScript playerScript = thePlayer.GetComponent().GetEnemyHealthBasedOnWaveNumber();
Any ideas? I could also be thinking of the totally wrong approach to the issue. Thank you.
p.s. also quite impressed you responded so quickly considering this was 7 years ago.