- Home /
how can you make a wrapper class for a character?
I'm trying to make a character class that contains all you need for a humanoid character because a prefab is just not working through different scenes.
I get the 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
I guess I want to know how to script character creation instead of using prefabs and having to set everything in every prefab. If my question is unclear please let me know.
here is an example of creating a character:
private List<HumanCharacter> _characters = new List<HumanCharacter>();
And here is an example of the class:
public class HumanCharacter : MonoBehaviour {
public Transform transform;
private AnimationClip[] _animations; //set in Unity, the animations each character has
private GameObject _myself;
private HumanCharacter() { } //DVC Not Allowed
//EVC
public HumanCharacter(GameObject prefab, Vector3 position, Quaternion rotation, AnimationClip[] Animations)
{
_myself = (GameObject)Instantiate(prefab, position, rotation);
_animations = Animations;
this.transform = _myself.transform;
if( !_myself.GetComponent("Animation").ToString().Equals("Animation") )
_myself.AddComponent("Animation");
AddAnimations();
}
...
Answer by YoungDeveloper · Dec 03, 2014 at 10:20 PM
Yes, you can't use new for class which inherits from MonoBehaviour. If you want the inspector look, monobehaviour is necessary. But most likely you don't, especially when things get hardcore OOP.
The structure really depends on the project requirements, difficulty and what are your future plans.
This is kind of setup i can image.
public class NetworkPlayer : MonoBehaviour {
private Player PLAYER;
//#Methods to handle server requests, your player related
private void ReceivePlayer(#someData){
PLAYER = new Player(#someData);
}
}
public sealed class Player{
public Player(#PlayerData){
this.name = #PlayerData.getName();
this.INVENTORY = #PlayerData.UnparseInventory();
}
private readonly string name;
private string guild;
private readonly Inventory INVENTORY;
}
public sealed class Inventory{
public Inventory(#Data){
slots = #Data.Unparse();
}
private byte WIDTH;
private byte HEIGTH;
private readonly BagSlot[] slots;
}
//SO ON
Only NetworkPlayer component will be place-able on unity gameobject. If you want to see classes and it's variables from inspector, use [System.Serializable] before class declaration. http://docs.unity3d.com/ScriptReference/Serializable.html
Hopefully, this will give you some ideas of how you can manage it.
I get the general Idea! Did you make your classes sealed to prevent unity from doing something, or is it just your structure?
You can't inherit from sealed classes. Structure is very important when is comes to security and/or if you develop in API form.