I'm calling getName() method from Achiv class on an ArrayList in printAchiv() method located in Achievements script and it throws an error.
Here is the error message that I get on the line Debug.Log("Achiv "+i+": "+ achivList[i].getName());:
Type
object' does not contain a definition forgetName' and no extension methodgetName' of typeobject' could be found (are you missing a using directive or an assembly reference?)
I'm just trying to access value of var "name" from obejct in 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;
    }
}
Achievements script :
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());
    }
}
                Use List<Achiv> instead of ArrayList. ArrayList is archaic, not type safe shouldn't be used anymore.
Indexer of ArrayList returns object that's why you get the error. Try the following.
public List<Achiv> achivList = new List<Achiv>();
Apart from this,
List publicly, prefer ReadOnlyCollection or IEnumerable.foreach over for unless there is a good reason.printAchiv doesn't follow proper naming convention, In c# we use "CamelCase", Rename it to PrintAchiv.Name.The problem is that the elements inside the ArrayList are stored as object. Thus achivList[i] returns an object, which does not provide the getName() method.
Either 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());
        }
    }   
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With