0

I have such a problem. I created a Character class. Also I created an ".asset" file and called it "Alice". I try to run a code:

[CreateAssetMenu(fileName = "New Character", menuName = "Character data", order = 51)]
public class Character : ScriptableObject {
    [SerializeField]
    public new string name;
    [SerializeField]
    public Color color;
}

public class TextPrinting : MonoBehaviour {

     public Text nameText;
     public Character Alice;

     void say (Character ingamecharacter) {
         nameText.text = ingamecharacter.name;
         nameText.color = ingamecharacter.color;
     }

     void Start() {
         say(Alice);
     }
}

But I have a NullReferenceException error on 15 line. I wrote a definition for nameText.

nameText = GameObject.Find("Canvas/Panel/NamePanel/NameText").GetComponent<Text>();

But I still have this error. So (I guess) the problem is that I need to write a definition for Alice Character. But I don't understand how can I do this if it's a Scriptable Object and I need to use file from Assets folder to do this.

What should I do? Or I do totally wrong thing?

Thanks.

1 Answers1

1

Here's what I would do.

Make Character a Monobehaviour:

public class Character : MonoBehaviour {
    public string name;
    public Color color;
}

Change the Alice variable to a GameObject, and add code to get the Character component from it:

public class TextPrinting : MonoBehaviour {

     public Text nameText;
     public GameObject Alice;

     void say (Character ingamecharacter) {
         nameText.text = ingamecharacter.name;
         nameText.color = ingamecharacter.color;
     }

     void Start() {
         say(Alice.GetComponent<Character>());
     }
}

Then, create an empty GameObject and put a Character component on it and you can define it how you'd like Alice to be.

Then save that GameObject as a prefab called "Alice".

Then drag the Alice prefab to the "Alice" field in your TextPrinting component.

Ruzihm
  • 19,749
  • 5
  • 36
  • 48