Good Night,
That’s my problem:
I made 4 Script: PHealth, PTarget, PAttack and Player.
I want to instantiate the first 3 scripts in the last script, to this i tried a lot of ways. The better way (i think) follows below:
C#
[SCRIPT]
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public PHealth ph = new PHealth();
public PAttack pa = new PAttack();
public PTarget pt = new PTarget();
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
[/SCRIPT]
Then i test it, the unity send me a message telling me this:
“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()”
I want to know how can i instantiate those class in the class Player??? What is the right way to write it?
Thanks!
Are you actually going to use the Start and Update functions? If not, remove them, and make the class not extend MonoBehaviour. If you are going to use MonoBehaviour functions in your class, you use AddComponent instead.
–Eric
Hi Eric thanks for the help,
i have another question… If i remove the MonoBehaviour, can i interact with the GameObjects and Transform class in the script? Better if i remove the MonoBehaviour what type of interaction can i lose?
Thanks!
If you remove the MonoBehaviour, you essentially lose all the methods defined in the API. That script would no longer be attached to a physical object in the scene (so no Transform). However, you can flip it around and attach GameObjects to it:
using System;
using UnityEngine;
public class Player
{
private GameObject Player;
public PHealth Health;
public PAttack Attack;
public PTarget Target;
public Player()
{
this.Player = new GameObject();
this.Health = this.Player.AddComponent<PHealth>();
this.Attack = this.Player.AddComponent<PAttack>();
this.Target = this.Player.AddComponent<PTarget>();
}
}
Then creating new players looks like:
Player player = new Player();
Debug.Log("Current Health: " + player.Health.CurrentHealth);
player.Target = SomeEnemy;
EDIT: Doing this might help make it easier to manage your game:
public static class Scene
{
public static List<Player> Allies = new List<Player>();
public static List<Player> Enemies = new List<Player();
}
Player ally1 = new Player();
Scene.Allies.Add(ally1);
Player enemy1 = new Enemy();
Scene.Enemies.Add(enemy1);
//go through all allies and reduce health
foreach (Player player in Scene.Allies)
{
player.Health.CurrentHealth -= 10;
}
Thanks for the help! This will help me a lot!