- Home /
Instantiate class from other script but same gameObject
I have two scripts in my Main Camera:
public class defaultBehavior : MonoBehaviour {
void Start () {
messages msg = new messages();
msg.isMsgEnabled = true;
msg.showMessage("teste");
}
void Update () {
}
}
and
public class messages : MonoBehaviour {
public bool isMsgEnabled = false;
public void showMessage(string message) {
if(isMsgEnabled) {
Debug.Log (message);
}
}
}
From defaultBehavior, how can I access my messages class, instantiate the isMsgEnabled bool and call the showMessage() void?
I've tried to instantiate with the new keyword but Unity throw me the following alert:
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all UnityEngine.MonoBehaviour:.ctor() messages:.ctor()
Answer by getyour411 · Aug 28, 2013 at 01:31 AM
Try this link, expand Section 1 - Accessing methods and variables
You should remove that link. I don't know where it originally pointed, but it is now pointing to a phishing site.
Answer by Azmodii · Aug 28, 2013 at 02:19 AM
Does the script need to inherit MonoBehaviour?
Try removing;
: MonoBehaviour
From the class declaration.
You can then access it via;
messages _messageClass = new messages();
Answer by TrickyHandz · Aug 28, 2013 at 01:51 AM
The messages class should not inherit from MonoBehaviour if you want to instantiate it. Also, you should add a constructor to handle everything you want to happen when a new instance of the class is created. Like this:
using UnityEngine;
public class messages
{
public bool isMsgEnabled;
// Constructor
public messages()
{
// Set isMsgEnabled to true
// when a new instance is created
isMsgEnabled = true;
}
public void showMessage(string message)
{
if (isMsgEnabled)
{
Debug.Log(message);
}
}
}
Next, your defaultBehavior script can be modified like so:
using UnityEngine;
public class defaultBehavior : MonoBehaviour
{
messages msg;
void Start()
{
messages msg = new messages();
msg.showMessage("test");
}
void Update()
{
}
}
I did this but now i'm receiving this message:
The class defined in the script file named 'messages' is not derived from $$anonymous$$onoBehaviour or ScriptableObject!
That doesn't means that messages should extend something?
If you already attached an instance of "messages" to a GameObject as a component when you removed the inheritance of $$anonymous$$onoBehaviour, you'll get that message. Simply remove the "messages" component from the GameObject and it will fix it.
All you need to use is the reference to the msg property on the defaultBehavior component to do all the work with it.
Your answer
Follow this Question
Related Questions
Behind the scenes voodoo w/ Instantiate 2 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
C# Utility Class 1 Answer