Hey there Toni,
I've been running into a slight issue regarding the Usable scripts OnUse event with prefabs and was wondering if you'd be able to help?
Right now I'm using the OnUse event to call a method with a passed gameobject that allows the player to hold the item.
That gameobject works fine on its own, but whenever I instantiate a prefab of it into a scene it'll load without the reference to the player method and grabbed gameobject since it has no reference of the player in the main scene.
I attempted to find a way to set the OnUse method and gameobject on the prefabs Start() method, but haven't been able to get it to work.
Any ideas?
Thanks!
Setting Usable OnUse event method through script
- pixelglitch
- Posts: 6
- Joined: Sun Sep 16, 2018 10:26 pm
- Location: Denver, CO
- Contact:
Re: Setting Usable OnUse event method through script
Hi,
There are two ways you can handle it:
1. Add a script to the Usable prefab that has a method that finds the player at runtime. In the inspector, assign this method to the OnUse() event. Example:
2. Or leave the OnUse() event unassigned, and assign it at runtime. Example:
There are two ways you can handle it:
1. Add a script to the Usable prefab that has a method that finds the player at runtime. In the inspector, assign this method to the OnUse() event. Example:
Code: Select all
public void TogglePickupOnPlayer(GameObject item)
{
var objectDragBehaviour = GameObject.FindWithTag("Player").GetComponent<ObjectDragBehaviour>();
objectDragBehaviour.TogglePickup(item);
}
Code: Select all
GetComponent<Usable>().events.OnUse.AddListener(() =>
{
var objectDragBehaviour = GameObject.FindWithTag("Player").GetComponent<ObjectDragBehaviour>();
objectDragBehaviour.TogglePickup(item);
});
- pixelglitch
- Posts: 6
- Joined: Sun Sep 16, 2018 10:26 pm
- Location: Denver, CO
- Contact:
Re: Setting Usable OnUse event method through script
You're the man Tony, appreciate the fast help and solid code samples.
Re: Setting Usable OnUse event method through script
Happy to help!