How to make a script tell another script to set something to true?
So I've been stuck on this forever. What I need is for my player script to set something in my robots script to true.
This is so when my player spawns the robot, it will know which way to go depending on what player spawned it.
Here is an example of the code that needs to be set to true by the player script.
void Update() {
if (IsPlayerOneSpawn == true)
{
MoveRight = true;
if (MoveRight)
{
transform.Translate(Vector3.right * Time.deltaTime);
}
}
Currently it will be set to false until it is spawned, then depending on what player spawned it, ether IsPlayerOneSpawn or IsPlayerTwoSpawn needs to be set to true.
Please someone tell me what I can do to solve this.
Answer by mrgenshyr · Jun 02, 2020 at 02:42 AM
To solve your problem first need to make the variables with the public statement at the Player's Script, here is an example:
public bool IsPlayerOneSpawn = false;
public bool IsPlayerTwoSpawn = false;
Then just call the Player's Script in the Robots Script and change the variables as you need:
public GameObject player;
//Or just: GameObject player = GameObject.Find("PlayerObjectName");
PlayerScript playerVar = player.GetComponent<PlayerScript>();
//Now you can access to player variables
if (playerVar.IsPlayerOneSpawn == true)
{
MoveRight = true;
if (MoveRight)
{
transform.Translate(Vector3.right * Time.deltaTime);
}
}
If you don't know for action the script without problems start at the Unity Editor selecting for your Player's Script the public GameObject player, and make sure that the scripts file names have been well written so you can access those vars that you needed.
Okay, I think I almost get it. One thing I'm not sure about is where do I put this line of code
PlayerScript playerVar = player.GetComponent();
Does this need to go in void update or something? I'm really not sure?
Also in my player script I have this for changing it to true
void Update() {
if (IsPlayerOne == true)
{
Calculate$$anonymous$$ovment();
SpawningRobot();
_IsPlayerOneSpawn = true;
}
Is there something else I should use to change _IsPlayerOneSpawn to true on the robots script?
thank you for your time.