- Home /
Item-Weapon Class
Hi everybody, i have written these classes:
Item : Monobehaviour
Abstract Weapon : Item
Gun : Weapon
//Methods that use Coroutine for fire, recoil and others..
public void RechargeGun()
{
StartCoroutine(Recharge());
}
private IEnumerator Recharge()
{
yield return new WaitForSeconds(RechargeTime);
}
This approach is correct?
If i try to instantiate a instance of Gun or Item and i initialize it, for example:
public Gun myGun = new Gun();
When i start the game, a message appear in the console: You are trying to create a Monobehaviour using the 'new' keyboard. This is not allowed. Monobehaviour can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all.
It's not error but this message alert me..
Thanks at all, i need your help.
Answer by jonnyhopper · Oct 28, 2013 at 09:49 PM
Yes, you cannot create anything that inherits from a Monobehaviour using new()
Instead you need to make a new game object and attach the component to it, for example:
GameObject myGunObject = new GameObject( "Gun" )
myGunObject.AddComponent< Gun >();
then you can do
Gun gun = myGunObject.GetComponent< Gun >();
gun.RechargeGun();
How would I add a graphical object to the gunObject as well?
Answer by RuggeriExtreme · Oct 28, 2013 at 09:54 PM
Ah, so i need a gameobject for initalize a new istance of Gun..
If I remove Item: Monobehaviour and i don't use the coroutine, the result is better?
I guess so but it really depends what you want to use it for. Do you want the gun to be attached to a character and so on, have a position and an update function etc etc?
In reality it is a very abstract concept. I have a lot of different type of weapons such as guns, spears, arcs and others, for each i need a method, for example Fire or Recharge, in the Weapon Class abstract i define these methods and in the subclass such as Gun, Arcs, Spear i implement them with a different function in relation with the weapon type..
Thanks for the reply
Your answer
Follow this Question
Related Questions
`DecalMode' could not be found 1 Answer
Reflect changes of script in editor 2 Answers
Invoking Effects of (Random) Items (C#) 0 Answers
Show GUITexture by picking an item. 0 Answers