Everything was working fine. If I place a cactus in the scene before I hit play, it will switch back and forth from idle to attack, but if I try to place a cactus I get this error:
NullReferenceException: Object reference not set to an instance of an object
DefenderSpawner.AttemptToPlaceDefenderAt (UnityEngine.Vector2 gridPos) (at Assets/Scripts/DefenderSpawner.cs:33)
DefenderSpawner.OnMouseDown () (at Assets/Scripts/DefenderSpawner.cs:23)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)
I have no trouble placing a trophy.
Here is the Defender Spawner Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DefenderSpawner : MonoBehaviour
{
Defender defender;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnMouseDown()
{
AttemptToPlaceDefenderAt(GetSquareClicked());
}
public void SetSelectedDefender(Defender defendertoSelect)
{
defender = defendertoSelect;
}
private void AttemptToPlaceDefenderAt(Vector2 gridPos)
{
var StarDisplay = FindObjectOfType<StarDisplay>();
int defenderCost = defender.GetStarCost();
if (StarDisplay.HaveEnoughStars(defenderCost))
{
SpawnDefender(gridPos);
StarDisplay.SpendStars(defenderCost);
}
}
private Vector2 GetSquareClicked()
{
Vector2 clickPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector2 worldPos = Camera.main.ScreenToWorldPoint(clickPos);
Vector2 gridPos = SnapToGrid(worldPos);
return gridPos;
}
private Vector2 SnapToGrid(Vector2 rawWorldPos)
{
float newX = Mathf.RoundToInt(rawWorldPos.x);
float newY = Mathf.RoundToInt(rawWorldPos.y);
return new Vector2(newX, newY);
}
private void SpawnDefender(Vector2 roundedPos)
{
Defender newDefender = Instantiate(defender, roundedPos, transform.rotation) as Defender;
}
}
I must have done something to break it, but I can’t find it.