- Home /
Manipulating one variable in a different script.
I've spent about six hours going through everything on here, stack overflow, and youtube. There's many explanations but I can't get a single one of them to actually work. I am trying to get a variable from another script, manipulate it, and then Debug.Log() all within the second script.
.
GameObject 1: GameMechanics
Script 1: MainGame
Variable: life (Life is also within Global)
.
Game Object 2: Player
Script 2: PlayerInfo
Variable: life
I want to get life from MainGame, put it into PlayerInfo, manipulate it across scripts in PlayerInfo, and debug.log it. Every example I find and follow just ends up throwing up about 20 mixed errors and I have no idea why..
Answer by Marioooo · Sep 09, 2020 at 06:31 PM
Hi! Hope i can be clear enough
public Class Script1 : Monobeaviour
{
public int variable = 10;
}
public Class PlayerInfo: Monobeaviour
{
// reference to the gameobject
public GameObject gameMechanics_GO;
// local variable, reference to the mainGame Script
private MainGame mainGameScript;
private void Start()
{
// create the reference
mainGameScript = gameMechanics_GO.GetComponent<MainGame>();
Debug.Log(mainGameScript.life);
}
}
attach the script to the correct gameObjects and don't forget to drag the manager gameobject to the reference on the player's script... now you can reference the mainGameScript to edit the life variable and you don't need to add a local variable to copy it.. just use the reference
Hope this helps!
It has helped enough for me to grasp how to manipulate it accordingly. This is a small test for something bigger that I'm trying to do and it relies heavily on things interacting/being consistent across scripts. Thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220613011537im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Handling character customization 0 Answers
Point Counter Works Only Once! 1 Answer
GetComponent won't work 1 Answer
Play animation of FPS player after hitting trigger 2 Answers
Cardboard VR app - add touch buttons to send keyboard arrows to scene 0 Answers