- Home /
fix script to get C# var from another object instead of object this script is attached to
I have this script which in theory I want it to disable the player's C# car controller script when the game over canvas it's attached to is enabled when the race is over. The problems I'm having that this script setup only works for other C# scripts that are attached to the object that has this script? To fix this is it as easy as putting the player object in a GameObject variable and just edit the GetComponent action to have the script find the player's controller script?
public class GameOverPause2P : MonoBehaviour {
public PlayerCar scriptPlayerCar;
public PlayerCar2 scriptPlayerCar2;
void Start()
{
scriptPlayerCar = GetComponent<PlayerCar> ();
scritpPlayerCar2 = GetComponent<PlayerCar2> ();
scriptPlayerCar.enabled = false;
scriptPlayerCar2.enabled = false;
}
// Update is called once per frame
void Update () {
}
}
Answer by toddisarockstar · Mar 27, 2018 at 06:43 AM
sounds like using static variables might be an easy solution if have a condition that is to be shared by all your cars. then no look ups are necessary.
public static bool RaceIsOver;
void Update () {
if (RaceIsOver==true) {
//if ANY car changes the bool to true
// all cars will do this here
//because static variables are
// shared by all
}
}
if you want to change or check a static variable from another script you simply would say:
//no lookup nessesary!!!!
nameOfScript.RaceIsOver = true;
Answer by YetiMoon · Mar 27, 2018 at 02:45 PM
public class GameOverPause2P : MonoBehaviour {
// reference the player GO's in order to retrieve their respective script components
public GameObject PlayerCar1;
public GameObject PlayerCar2;
public PlayerCar scriptPlayerCar;
public PlayerCar2 scriptPlayerCar2;
// game over is false by default
public bool GameOver = false;
void Start()
{
// grab the script component for both players
Player1CarControllerScript = PlayerCar1.GetComponent<ScriptPlayerCar>();
Player2CarControllerScript = PlayerCar2.GetComponent<ScriptPlayerCar2>();
scriptPlayerCar = GetComponent<PlayerCar> ();
scriptPlayerCar2 = GetComponent<PlayerCar2> ();
scriptPlayerCar.enabled = false;
scriptPlayerCar2.enabled = false;
}
// Update is called once per frame
void Update () {
if (GameOver == true) {
// disable CarControllerScript component attached to player
Player1CarControllerScript.enabled = false;
Player2CarControllerScript.enabled = false;
}
}
}
Your answer
Follow this Question
Related Questions
Add and destroy instantiated gameobject in linkedlist C# 1 Answer
error CS0118: `New_Career.Fame' is a `field' but a `type' was expected 1 Answer
Find GameObjects with a true boolean and put them in an array? 1 Answer
Setting a variable to a variable from another script 1 Answer
Trigger not getting GameObject 2 Answers