Other
Answer was solved by using a vector3 variable in onclick.addlistener instead of grabbing the vector3 directly from the onCollission list. I feel this may be some sort of bug, but I could be wrong.
onClick.AddListener IndexOutOfRangeException error and listener not seen in inspector
I am trying to make a simple system where a player can warp to any nearby warp pad. I am able to properly get all warp pads (layermask'ed) within the wanted distance, and properly instantiate and display the buttons in "warpScreen" (blank panel with horizontal guide). When I click the button, the error shoots back out at me on ONLY the buttons being instantiated from the for loop (looping through Colliders list of found warpPads). My "Exit" button works perfectly fine.
void WarpPadCheck()
{
RaycastHit hit;
if (Physics.Raycast(body.transform.position, -Vector3.up, out hit))
{
if (hit.transform.gameObject.layer == 8)
{
warpScreen.SetActive(true);
Collider[] hitColliders = Physics.OverlapSphere(hit.transform.position, 200f, warpPadMask);
GameObject newB = Instantiate(button) as GameObject;
newB.SetActive(true);
newB.transform.SetParent(warpScreen.transform, false);
newB.transform.GetChild(0).GetComponent<Text>().text = "Close";
newB.GetComponent<Button>().onClick.AddListener(() => CloseWarpWindow());
for (int i = 0; i < hitColliders.Length; i++)
{
if (hitColliders[i].transform != hit.transform)
{
GameObject newButton = Instantiate(button) as GameObject;
newButton.SetActive(true);
newButton.transform.SetParent(warpScreen.transform, false);
newButton.transform.GetChild(0).GetComponent<Text>().text = hitColliders[i].name;
newButton.GetComponent<Button>().onClick.AddListener( () => WarpPlayer(hitColliders[i].transform.position));
}
}
}
}
}
public void WarpPlayer(Vector3 newPosition)
{
body.transform.position = newPosition;
foreach (Transform child in warpScreen.transform)
{
Destroy(child);
}
WarpPadCheck();
}
public void CloseWarpWindow()
{
foreach(Transform child in warpScreen.transform)
{
Destroy(child.transform.gameObject);
}
warpScreen.SetActive(false);
}
Follow this Question
Related Questions
Instantiated button prefab causes Delegation error on click and does not add OnClick Listener 0 Answers
Array index is out of range??? (Day Night Cycle Script) 1 Answer
Array index is out of range (C#)? 1 Answer
My Script just won't work at all? 2 Answers
Unity C# array index is out of range 1 Answer