Home > Back-end >  How to assign a property to a class in Unity?
How to assign a property to a class in Unity?

Time:09-29

New to Unity, working on an infectious disease simulation. I have a "patient" class to which I want to assign a "disease". To start, I just want to be able to print the patient's disease to console on spawn. How do I go about this? Here's my current attempt:

public class Disease : MonoBehaviour
{
    public string[] diseases = new string[] {"Pneumonia", "Influenza", "Covid-19"};
}

public class Patient : MonoBehaviour
{
    public Disease disease;
    void Start()
    {   
        disease = Disease.diseases[Random.Range(0, diseases.Length)];
        Debug.Log("Patient has: "   disease);
    }
}

I get these errors:

  1. error CS0120: An object reference is required for the non-static field, method, or property 'Disease.diseases'
  2. error CS0103: The name 'diseases' does not exist in the current context

Thanks.

CodePudding user response:

You are trying to reach an object property through its class as if it is a static property. Change your diseases property in Disease class to be static and also change this line to this, because you forgot to type Disease:

// In Disease class
public static string[] diseases = new string[] {"Pneumonia", "Influenza", "Covid-19"};

// In patient class
disease = Disease.diseases[Random.Range(0, Disease.diseases.Length)];

Also you cant assign that value to the disease because its an Disease object and value this line returns is a string so change disease to be a string like this:

public class Patient : MonoBehaviour {

    public string disease;
    ...
}

Note : You can also think about removing MonoBehaviour from Disease class if you are not thinking about attaching it into a GameObject.

CodePudding user response:

If you have these code in two different scripts and have attached them to a gameobject the following solution will work:

Patient:

public class Patient : MonoBehaviour
{
    public Disease disease;
    public string dis;
    void Start()
    {
        dis = disease.diseases[Random.Range(0, disease.diseases.Length)];
        Debug.Log("Patient has: "   dis);
    }
}

Disease:

public class Disease : MonoBehaviour
{
    public string[] diseases = new string[] { "Pneumonia", "Influenza", "Covid-19" };
}

But this doesn't work if you don't attach to gameObject because you obviously need to attach it so the start function works... So this is what i did: Created an empty gameObject -> put both your scripts in it -> referenced Dicease script into patient script by drag and dropping in inspector -> And the changes in code thats there in the answer -> the code works.

  • Related