- Home /
Referencing a non static variable from another script C# Unity
I'm trying to make a game where the player can chose the color of their ship. This process involves two scripts.
Script 1: "ColorPicker" The player will press one of four buttons to select their ship's color. This is recorded as a number in the variable "int color" This process does work, I can tell from the "Debug.Log". However this variable cannot be private or static or the code won't work.
public Sprite[] shipcolors;
public int color;
public void ColorChoice(int color)
{
Debug.Log(color);
}
Script 2: "PlayerControler" This script controls all the behaviors of the player's ship, among those what color it is.
public Sprite[] shipcolors;
public GameObject colorpicker;
void Start () {
ColorChoice();
}
public void ColorChoice()
{
colorpicker = GameObject.Find("ColorPicker");
ColorPicker colorScript = colorpicker.GetComponent<ColorPicker>();
print("Color Chosen: " + colorScript.color);
if (shipcolors[colorScript.color])
{
this.GetComponent<SpriteRenderer>().sprite = shipcolors[colorScript.color];
}
}
From the print statement I see that the color variable is always set to zero no matter what button I press. I'm trying to figure out why "int color" saves in the "ColorPicker" script but doesn't transfer over to the "PlayerController" script.
If I manually enter the number into the color field while I am playing the game it will change the ship to the correct color but I want it to save from the buttons so the player doesn't have to enter the number manually. I've tried putting the code from the "ColorPicker" script into the "PlayerController" script but I never got that to work. Any suggestions?
Answer by UnityCoach · Apr 15, 2017 at 12:58 PM
I don't see where you save the color int.
public Sprite [] shipcolors;
public int color;
public void ColorChoice (int color)
{
Debug.Log (color); // here you debug the incoming color, not the member, you need to add
color = color; // I would suggest you change one of the two names for disambiguation
}
Thanks @UnityCoach and @Commoble I added this.color = color and it works now
Your answer
Follow this Question
Related Questions
2 animations keep switching at a rapid pace 1 Answer
Unloading Broken Assembly | How to solve this !? 2 Answers
How to make sure than one script affect the player of the specific client, and not the other 2 Answers
The spaceship acceleration script is good ? And how to use it with engine ? 0 Answers