How do you set a variable to a prefab variable?
I am having a bit of an issue trying to do this using C#.
OK, so I have a prefab with a 'don't destroy on load'. This comes up on the main menu scene and goes though out each scene. If the player comes back to the main menu, then it checks to see if one exists so it does not recreate it. That works fine. This prefab is 'weather'.
-On the prefab I have 4 game objects that need to be set on or off. Each has its own tag 'snow-1', snow-2', rain-1' and 'rain-2'.
On the main menu scene I have a script that is supposed to find these prefabs by tag and turn them on or off when the player changes the setting. This gives and error.
There is some issue with how the code is set to address the instance of the object. This should be an easy fix for a skilled programmer (which I am not).
Here is the script that is attached to the weather prefab. public class WeatherDontDestroy : MonoBehaviour { ////////////////////////////////////////////////////////////////////////////////////// void Awake () { DontDestroyOnLoad(transform.gameObject); } ////////////////////////////////////////////////////////////////////////////////////// }
Here is the code on the main menu script. I just included the pertinent info.
public class MainMenu : MonoBehaviour
{
public GameObject rain1;
public GameObject rain2;
public GameObject snow1;
public GameObject snow2;
public GameObject weatherPrefab;
////////////////////////////////////////////////
if (!GameObject.Find("Weather"))
{
Instantiate(weatherPrefab, Vector3.zero, Quaternion.identity);
}
rain1 = GameObject.FindWithTag("rain1");
rain2 = GameObject.FindWithTag("rain2");
snow1 = GameObject.FindWithTag("snow1");
snow2 = GameObject.FindWithTag("snow2");
////////////////////////////////////////////////
//Set up weather with name
switch (weatherInt)
{
case 1: //Clear Sky
rain1.gameObject.SetActive(false);
rain2.gameObject.SetActive(false);
snow1.gameObject.SetActive(false);
snow2.gameObject.SetActive(false);
text4.text = "Clear Sky";
break;
Here is the error: NullReferenceException: Object reference not set to an instance of an object MainMenu.Start () (at Assets/MiniGolf/Scripts-1/MainMenu.cs:165)
Now, it seems at the point rain1 = GameObject.FindWithTag("rain1"); it is not copying over the variable.
Answer by RandomCharacters · Sep 30, 2015 at 08:10 PM
OK, so I found out part of the problem. The game objects in the project folder must be active at the start. They were inactive. So now they assign OK.