I’m a total hack when it comes to scripting in C#, but I’m slowly getting the hang of it. I’m at a complete loss for why I’m getting errors when calling a method on a gameobject directly, when it works perfectly when I call it via a raycast. I’ll do my best to explain and show code examples below. I’d appreciate any help you’re willing to give. Thanks!
When I wrote the first iteration of my program, I used a raycast to detect if a gameobject was clicked, and then ran a script within that gameobject. It does this by passing the hit gameobject to the gamemanager, which executes it based on whatever gametype is currently being used. My code looks like this…
void Update()
{
// Is the mouse over a Unity UI element
if (EventSystem.current.IsPointerOverGameObject())
{
// If so, don't interact with the hexes
return;
}
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo) )
{
GameObject ourHitObject = hitInfo.collider.transform.parent.gameObject;
selectedHex = ourHitObject;
if (Input.GetMouseButtonDown(0))
{
// Print hit hex name to the console (When clicking center hex, returns "Hex10_10")
Debug.Log("Raycast hit: " + hitInfo.collider.transform.parent.name);
// Informs the GameManager that a hex space has been clicked on
gameManager.GetComponent<GameManager>().HexSelected(ourHitObject);
}
}
}
After the gameobject is passed along to the game manager, it simply executes the PlaceTile() function of that object. Easy as pie…
// Called from the GameManager (via the MouseManager) whenever a hex location on the board is selected
public void HexSelected(GameObject selected) // Passes in the selected hex on the game board
{
selected.GetComponent<HexManager>().PlaceTile(HexAbrevText, HexValue);
selected.GetComponent<HexManager>().NotifySurroundingHexes(HexAbrevText);
}
The above method works perfectly. However, for certain gametypes I need the AI to place tiles to set up the board at the beginning of the game. It seems to me that I should be able to simply write a script that calls the PlaceTile() function of whatever hex I choose. It works to a point, placing the tile on the board and setting certain values of said tile. However, as it runs through its other checks and calculations, it encounters an UnassignedReferenceException:
UnassignedReferenceException: The variable upperRightHex of HexManager has not been assigned.
This variable is one of the center hex’s neighboring hex pieces, and Unity claims it isn’t assigned, but it is. I wrote a script that finds and stores it at startup, and I can clearly see it assigned in the editor while the game is running.
So my question is, what is different about the gameobject that the raycast returns, as opposed to directly calling the gameobject in script? Why does the first method work perfectly, and the second method has issues?
Thanks in advance!
Brett