I am trying to create a “Window” with unity’s UI system.
When I click a “Castle” tile I want to see the window and it’s TitleBar display some text.
It has a bunch of nested GameObjects.
There are two parts to my code, A CastleScript which handles the click and instantiates a new window. And a script attached to the window which will let me set the text (to anything other than “New Text”.
Town Window Script :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TownWindowScript : MonoBehaviour {
public Transform WinPrefab;
public Transform TownWindow;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseDown()
{
string s;
s = "";
Debug.Log("TownWindowScript.cs OnMouseDown() (This will instantiate)");
TownWindow = Instantiate(WinPrefab);
TownWindow.tag = "Window-Town";
//TownWindow.GetComponent<WindowScript>().WindowTitle = GetComponent<CastleScript>().TownName;
s = GetComponent<CastleScript>().TownName;
TownWindow.GetComponent<WindowScript>().SetWindowTitle(s);
Debug.Log("Done");
//Transform t = TownWindow.transform.Find("TitleBarText");
//Text tt = t.GetComponent<Text>();
//tt.text = "asdf";//GetComponent<CastleScript>().TownName;
}
}
And the Window Script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class WindowScript : MonoBehaviour {
private Transform BackPanel;
private Transform FloatingWindow;
public string WindowTitle;
//Used for initializeation after all (sub?) objects have been instantiated
void Awake()
{
Debug.Log("WindowScript.cs Awake()");
if (tag == "Window-Town")
{
Debug.Log("Here");
//setup Window Tile Text
if (WindowTitle == "") { WindowTitle = "New Window"; }
else
{
Transform t = transform.Find("WindowTitle");
t.GetComponent<Text>().text = WindowTitle;
}
}
}
// Use this for initialization
void Start () {
Debug.Log("WindowScript.cs Start()");
//Get Window Segments
BackPanel = transform.Find("BackPanel");
FloatingWindow = transform.Find("FloatingWindowPanel");
//Disable segments by type
if (tag == "Window-Town")
{
//Don't use back panel for town
BackPanel.gameObject.SetActive(false);
GameObject[] go = GameObject.FindGameObjectsWithTag("Window-Town");
//Only allow one Town Window
if (go.Length > 1 ) { Destroy(transform.root.gameObject); }
}
else if (tag == "Window-Menu")
{
FloatingWindow.gameObject.SetActive(false);
}
}
// Update is called once per frame
void Update () {
}
public void SetWindowTitle(string s)
{
Transform t;
t = transform.Find("TitleBarText");
t.GetComponent<Text>().text = s;
}
}
When I click the castle I get a window, but the text is the default “New Text” not my dynamic castle name.
The Console displays:
TownWindowScript.cs OnMouseDown (This will instantiate)
WindowScript.cs Awake()
Null Reference Exception (WindowScript.cs Line 59)
WindowScript.cs Start()
I expect that my child objects are not created when I call SetWindowTitle. Does anyone have suggestions or work arounds for this?

