I currently have a setup where I can look at items and pick them up (destroy them for now ?) via this script: Pickup Items Script
using UnityEngine;
using System.Collections;
public class PickupItems : MonoBehaviour {
public float interactDistance = 3;
int pickupsLayerMask;
int screenX;
int screenY;
// Use this for initialization
void Start () {
screenX = Screen.width / 2;
screenY = Screen.height / 2;
pickupsLayerMask = LayerMask.GetMask ("Pickups");
}
// Update is called once per frame
void Update () {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(new Vector3(screenX, screenY));
if (Physics.Raycast (ray, out hit, interactDistance, pickupsLayerMask )) {
Debug.Log("Pickup!" + Time.time);
Destroy(hit.transform.gameObject);
}
}
}
And instead of just destroying the objects, which currently is just a testing mechanism kinda thing, I would like to make it so I call a function specific to the type of item that it is, so perhaps like if it was a door it wouldn’t actually destroy it would just swing open (probably gonna change the script to “interactblahblahblah”)
This is kind of a for instance, as it also interests me to make it so that like when an item is in my inventory and I use it, then it will also run a specific function for that kind of item.
I have a feeling I will need to use inheritance but I don’t have much of an idea of how that can be done in unity.
This is the perfect use case for an interface. Create an interface like IUseable with a Use() method. Implement it on the appropriate MonoBehaviours (like a DoorHandler script) and then you can interact with any object generically.
Would I not have to have the script file name to call it? I am under the impression that I would have to make a different case for each component.
Such as getting the DoorHandler script and then calling it. and for each different type of item I would need to get a reference to that script
NullReferenceException: Object reference not set to an instance of an object
Interact.interaction (RaycastHit hit) (at Assets/Scripts/Player/Interactions/Interact.cs:74)
Interact.Update () (at Assets/Scripts/Player/Interactions/Interact.cs:58)
Any ideas? Should I make it an actual object like in your code?
Then add scripts that implement IUseEvent to your items:
// DestroyOnUse.cs:
public class DestroyOnUse : MonoBehaviour, IUseEvent {
public void Use() {
Destroy(this.gameObject);
}
}
// AnimateOnUse.cs:
public class AnimateOnUse : MonoBehaviour, IUseEvent {
public string animatorState;
public void Use() {
GetComponent<Animator>().Play(animatorState);
}
}
etc.
Finally, in your PickupItems script, instead of Destroy(), execute the event: