Returning new class from a method not working

Hi,

I am trying to run a method that returns a class with an int and a bool. Problem is that no matter what int and bool value the method returns it always is received as 0 and false.


Here is my method that runs the operation:

public void CheckSomething(something)
{
    ReturnClass returnClass = otherScript.CheckForItem(something);

    Debug.Log(returnClass.exists); //prints false to the console
    Debug.Log(returnClass.index); //prints 0 to the console

    if (returnClass.exists)
    {
        DoSomething(returnClass.index, something); //this should run, but does not because returnClass.exists == false
    }
}

And here is the method that returns the class:

(I simplified it to always return the same values for testing purposes)

public ReturnClass CheckForItem(string item)
{
    //checking if the item exists and the index of the item

    return new ReturnClass(true, 3);
}

And here is the class I am returning:

public class ReturnClass
{
    public int index;
    public bool exists;

    public ReturnClass(bool foundItem, int indexOfItem)
    {
        int index = indexOfItem;
        bool exists = foundItem;
    }
}

Am I doing something wrong?

Thanks in advance for any answers :slight_smile:

Notice how in this class you define “int index” and “bool exists” inside the constructor?

 public class ReturnClass
 {
     public int index;
     public bool exists;
 
     public ReturnClass(bool foundItem, int indexOfItem)
     {
         int index = indexOfItem;
         bool exists = foundItem;
     }
 }

By defining the type of variable or field, you actually allocate ram to a new local field of that type, IE, you’re parameters are never actually being passed to the fields of the class. You need to use THIS keyword in front of the fields or reference the fields by default, like this.

 public class ReturnClass
 {
     public int index;
     public bool exists;
 
     public ReturnClass(bool foundItem, int indexOfItem)
     {
         index = indexOfItem;
         exists = foundItem;
     }
 }