In a C# script i tried this
First file:
class Ada{
int n;
}
Another file:
class Bada{
Ada myAda;
void start(){
myAda = new Ada();
myAda.n = 3;
}
}
ANDDD IT didn’t work. I got error like
“You are trying to create a MonoBehaviour using the NEW keyword. This is not allowed”
So then, how do i access those variables?
Say you have class Ada. Make it derive from Monobehaviour. You need to set the variable as public to be accessed from other scripts, in C# by default, they are private.
using UnityEngine;
using System.Collections;
public class Ada : MonoBehaviour
{
public int n;
}
Then your class Bada
using UnityEngine;
using System.Collections;
public class Bada : MonoBehaviour
{
public GameObject go;
void Awake()
{
go.GetComponent<Ada>().n = 3;
}
}
This would require you to attach Ada to a GameObject, as well as Bada. Assign the public GameObject in the inspector. If you have Ada and Bada attached to the same GameObject, simply use GetComponent instead of go.Getcomponent. If you don’t want Ada attached to a GameObject, you’ll need ‘n’ to be static.
using UnityEngine;
using System.Collections;
public static class Ada : System.Object
{
public static int n;
}
Then, from another script, you’d simply call ‘n’ like:
Ada.n = 3;
But the best advice I can give, do some homework, have a look at the Unity Script Reference, Unity Tutorials, and MSDN C# Reference. Hope this helps.
Linus
3
Look up GetComponent in the documentation or one of the many other similar questions here at Unity Answers
The error is probably because Ada inherits from Monobehaviour which makes it a component. You have to use Instantiate to create it.