Call function of a MonoBehaviour class in another class
So i am trying to call a function in this class: using UnityEngine; using UnityEngine.UI; using System.Collections;
public class AchievementDisplay : MonoBehaviour {
Text text;
void Start()
{
gameObject.SetActive(true);
text = GetComponent<Text>();
}
void Update () {
}
public void achievementActivate(string achText) {
Debug.Log("PLEB");
text.text = achText;
moveUp();
}
void moveUp() {
var t = 0;
while (t < 100) {
transform.Translate(Vector3.up * Time.deltaTime);
}
Invoke("moveDown", 5);
}
void moveDown() {
var t = 0;
while (t < 100)
{
transform.Translate(Vector3.down * Time.deltaTime);
}
}
}
via this class: using UnityEngine; using System.Collections; using System.Collections.Generic; using System;
public class AchievementManager : MonoBehaviour {
// This class is used to check for achievements and give. I have no idea how to do this. Help would be cool.
List<Achievement> ach = new List<Achievement>();
List<Achievement> activatedAch = new List<Achievement>();
AchievementDisplay achievedis = new AchievementDisplay();
void Start () {
ach.Add(new Achievement(2, "clicks", "poopie"));
}
void Update () {
foreach(Achievement achie in ach){
if (achie.theSomething == "clicks"){
if(achie.amountOfSomething == Data.clicks){
achie.activated = true;
}
}
if (achie.activated) {
achie.activated = false;
activatedAch.Add(achie);
achievedis.achievementActivate(achie.text);
ach.Remove(achie);
}
}
}
}
But i am getting this error: 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() AchievementDisplay:.ctor() AchievementManager:.ctor()
Is there a good way to do this?
as the error states, you're trying to new
a $$anonymous$$onoBehaviour where you should be using AddComponent()
.
if you want to get a reference to the AchievementDisplay
on another game object then use GetComponent()
after finding the object in question (either by storing a reference to its game object or using Find()
I would recommend you to see the following link, I think it is a suitable answer for you.
http://answers.unity3d.com/questions/451004/how-to-call-a-function-from-one-class-to-another-c.html
Your answer
Follow this Question
Related Questions
Array.Sort() - JS only???! 0 Answers
Calling Function from another script not working 1 Answer
Function not running everytime 0 Answers