Can't call my method on object from arraylist
So my problem is: I am trying to call the getName () method from the Achiv class on the ArrayList in the printAchiv () method located in the Achievements script and it clearly does not work.
Here is the error I am getting on this line in the Achievements script: -> Debug.Log ("Achiv" + i + ":" + achivList [i] .getName ());
Enter
object' does not contain a definition for
getName 'and no extension methodgetName' of type
object' can be found (are you missing using directive or assembly reference?)
I'm just trying to access the var "name" value from obejct in a collection.
Achiv class
using UnityEngine;
using System.Collections;
public class Achiv : MonoBehaviour {
public string name;
public Achiv(string name )
{
this.name= name;
}
public string getName()
{
return name;
}
}
Script achievements
using UnityEngine;
using System.Collections;
public class Achievements: MonoBehaviour {
public ArrayList achivList = new ArrayList();
void Start ()
{
achivList.Add (new Achiv("First name", "Descirptionn", false));
achivList.Add (new Achiv("Second name", "Descirptionnn", false));
printAchiv();
}
void printAchiv(){
for (int i = 0; i <= achivList.Count - 1; i++)
Debug.Log("Achiv "+i+": "+ achivList[i].getName());
}
}
source to share
Use List<Achiv>
instead ArrayList
. ArrayList
is archaic and type safe should not be used anymore.
The pointer ArrayList
returns object
why you are getting the error. Try the following.
public List<Achiv> achivList = new List<Achiv>();
Besides,
- Do not publish
List
publicly, preferReadOnlyCollection
orIEnumerable
. - Prefer
foreach
overfor
unless there is a good reason. -
printAchiv
does not match the correct naming convention. In C # we are using "CamelCase", rename it toprintAchiv
. - get / set methods are for java style languages ββthat don't support properties. In C #, we use properties instead. Create a property viz
Name
.
source to share
The problem is that the elements inside ArrayList
are stored as object
. Thus, it achivList[i]
returns object
, which the method does not provide getName()
. Or you can add a cast:
Debug.Log("Achiv "+i+": "+ (Achiv)achivList[i].getName());
or you can switch to a generic list:
using UnityEngine;
using System.Collections.Generic;
public class Achievements: MonoBehaviour {
public List<Achiv> achivList = new List<Achiv>();
void Start () {
achivList.Add (new Achiv("First name", "Descirptionn", false));
achivList.Add (new Achiv("Second name", "Descirptionnn", false));
printAchiv();
}
void printAchiv(){
for (int i = 0; i <= achivList.Count - 1; i++)
{
Debug.Log("Achiv "+i+": "+ achivList[i].getName());
}
}
}
source to share