Attach a non-MonoBehaviour Class from another Script to an Instantiated Button
I want the see the properties of the class Room from another script in the Inspector of an instantiated Button. It only works when I set class Room to MonoBehaviour, but than I get some warning when I try to create objects out of Room in the class CreateRoom.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Room {
public int RoomNR;
}
Create Rooms looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CreateRoom : MonoBehaviour {
public Room room;
public GameObject RoomButtonPrefab;
void Start()
{
GameObject RoomButtonPrefabClone = Instantiate(RoomButtonPrefab, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
RoomButtonPrefabClone.transform.SetParent(GameObject.FindGameObjectWithTag("Canvas").transform, false);
RoomButtonPrefabClone.AddComponent<Room>();
}
}
When I try this it says: The type 'Room' cannot be used as type parameter 'T' in the generic type or method 'GameObject.AddComponent()'....
What can I do to solve this?
You have no choice but making Room
inherit from $$anonymous$$onoBehaviour
(or Component
) if you want to use AddComponent
.
An other solution would be to have something like a Dictionnary of <GameObject,Room>
and associate a given room to the desired gameobject.
Answer by umut91c · Jan 09, 2018 at 03:31 PM
Thanks for the info. I think I will pass on the AddComponent feature.
Your answer
![](https://koobas.hobune.stream/wayback/20220612150051im_/https://answers.unity.com/themes/thub/images/avi.jpg)