- Home /
Problem with adding custom class object to a List
My problem is simple:
Script "Trigger", not attached to any gameObject, just sitting in the Assets/Resources folder.
using UnityEngine;
using System.Collections;
public class Trigger : MonoBehaviour {
public GameObject triggerObject = new GameObject();
public string triggerType = "";
public Coordinate coords = new Coordinate();
}
Script "Switch", attached to a gameObject that represents a pushable button/switch.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Switch : MonoBehaviour {
public List<Trigger> onTriggers;
void Start () {
onTriggers = new List<Trigger>();
}
public void AddOnTrigger(GameObject obj) {
Trigger newTrigger = new Trigger();
onTriggers.Add (newTrigger);
onTriggers[onTriggers.Count - 1].triggerObject = obj;
}
}
With AddOnTrigger(), I want to 1. add a new Trigger to the onTriggers List, and 2. set the triggerObject that is part of the Trigger class.
However, when the function is called, a trigger is added to the list (list size increased acordingly), but the inspector shows "None (Trigger)" in the list's fields, and the triggerObject is still null.
When I had the Trigger class locally as part of the Switch script, it worked flawlessly. What am I doing wrong?!?
Answer by Cherno · May 06, 2014 at 05:30 PM
I have found the solution:
The custom class can't extend Monobehaviour, so instead of
public class Trigger : MonoBehaviour {
we need
public class Trigger {