IndexOutOfRangeException: Index was outside the bounds of the array. (wrapper stelemref) System.Object.virt_stelemref_class(intptr,object)
Hey, Im sry if this question is already asked anywhere but I searched in other Questions with this topic to solve my problem but i found no answer yet. I am very new in programming with C# in Unity so Im not rlly sure why I get this ErrorLog. This is my Code:
public PhotonView[] photonViews; public GameObject[] GOsWithPhotonView;
void GetPhotonViews()
{
GOsWithPhotonView = GameObject.FindGameObjectsWithTag("PhagenPlayer");
int arrayLength = GOsWithPhotonView.Length;
foreach(GameObject GO in GOsWithPhotonView)
{
for(int i = 0; i < arrayLength; i++)
{
photonViews[i] = GO.GetComponent<PhotonView>(); X
}
}
}
The Error is in the Line i marked with the X. I also tried to init the PhotonViews[] array with new PhotonViews[10] to be sure the array is big enough because in my Test there is only one GameObject with a PhotonView with the Tag "PhagenPlayer" but I get this error nevertheless. Maybe someone could help me, I would be very grateful.
Answer by Captain_Pineapple · Aug 14, 2020 at 10:00 AM
Hey there,
you already correctly realized that you need to initialize your array. An array is always of fixed size. For that reason it is not really fitting for the thing you are trying to do here.
There are dynamic data types that are better suited here like for example a List
.
so instead of Photonview[]
you write List<PhotonView>
to create a list. You need to include using System.Collections.Generic
in your code as well. A list can always dynamically be appended to or removed from using photonViews.Add(...)
and photonViews.Remove(....)
. You can also still access all elements by a numeric index like you do with an array.
Hope this helps, let me know if something was unclear.
Your answer
Follow this Question
Related Questions
Problem instantiating projectiles 1 Answer
Doubt about placing items on tables 1 Answer
Index out of range error 1 Answer
least 'expensive' way to go through list and check transform.position 0 Answers
Array index is out of range. c# 2 Answers