- Home /
Call method from attached Gameobject
Hey, I just started learning Unity and C#.
In example below a Gameobject named HealthPotion with a script named HealthPotion is attached to the "public Gameobject itemGameobject".
On a button pressed, Use() in itemConsumable is called. In example below I wanna call Use() on HealthPotion via Use() on ItemConsumable without having to instantiate itemGameobject.(Use() is static)
When i type "HealhPotion.Use();" in Use() from ItemConsumable it works obviously, but i want this Dependent from attached Gameobject. So it should be somethink like "itemGameobject.Use()".
Hope my question is clear
public class ItemConsumable : Item
{
public GameObject itemGameobject;
public override void Use()
{
}
public class HealthPotion : MonoBehaviour
{
public static void Use()
{
GameObject.FindGameObjectWithTag("Player").SendMessage("Heal", 3);
Debug.Log("healed!");
}
}
There is a lot that you are doing slightly confused here. Let me write up an example with comments. One sec.
Answer by sacredgeometry · Aug 17, 2019 at 12:12 PM
Your Player Type
public class MyPlayer : MonoBehaviour
{
public IItem CurrentItem;
public int Health = 100;
void Update()
{
if(CurrentItem != null && Input.GetKeyDown(KeyCode.Space))
{
CurrentItem.Use(this);
}
}
}
Your item Interface
public interface IItem
{
void Use(MyPlayer player);
}
Your Item that implements the IItem interface
public class HealthPotion : MonoBehaviour, IItem
{
public int Health;
public void Use(MyPlayer player)
{
// Do item code and any destruction to item needed here
player.Health += Health;
}
}
I did it a bit different but it works with Interface. Thanks!
:) There are a million and one ways to do this. Implementing to interfaces is generally a good idea because it keeps things nice and loose/ decoupled.
@Rimonof Also I was making you a video explanation haha I guess you dont need it anymore.