- Home /
calling a child class method in OnMouseDown() of sprite.
Good Day all, I am trying to make a simple 2D game and here is how it works. Assume there is a sprite "tent", and whenever i clicked the tent, the console will print out a message. Sounds straightforward is it? However I'm like stuck in the middle of it and I know I am gonna facepalmed myself so hard after this. What I did in my script is:
I got abstract base class of name "Parent" and it has a function sleep()
public abstract class Player { protected string _name;
public Player(string name) { _name = name; } public string Name { get{ return _name; } set{ _name = value; } } //TESTING : SLEEP FUNCTION public void Sleep() { Debug.Log("activated"); } }
Next I have a child class called Civilian
public class Civilian : Player {
public Civilian(string name):base(name) { } }
Then in my script "Tentclicked", i want to called the function of sleep when the sprite is clicked.
public class tentclicked : MonoBehaviour {
void OnMouseDown() { c.Sleep(); } }
And you are wondering what is c and what it is point to? I instantiated a new class in another script called testing1.
public class testing1 : MonoBehaviour
{
public Text p1name;
// Use this for initialization
void Start()
{
if (Choosechar.choice.choicecount == 1)
{
Civilian c = new Civilian(Testingsavename.playernames.username);
p1name = GetComponent<Text>();
p1name.text = c.Name;
}
if (Choosechar.choice.choicecount == 2)
{
Professor p = new Professor(Testingsavename.playernames.username);
p1name = GetComponent<Text>();
p1name.text = p.Name;
}
if (Choosechar.choice.choicecount == 3)
{
Native n = new Native(Testingsavename.playernames.username);
p1name = GetComponent<Text>();
p1name.text = n.Name;
}
if (Choosechar.choice.choicecount == 4)
{
Fisherman f = new Fisherman(Testingsavename.playernames.username);
p1name = GetComponent<Text>();
p1name.text = f.Name;
}
}
// Update is called once per frame
void Update()
{
}
}
I have already add a circle collider to my sprite. The error is that in tentclicked, c does not exist in context. So i suspect it may be that unity does not know what c is. I am thinking of making civilian class a static one, and just called Civilian.civilian.Sleep() in tentclicked script....