- Home /
How can I share code between simple intractable objects in a first person game.
I'm making a simple first person game. The main camera/player shoots a raycast that sees if a player is close enough to interact with an object.
void Update(){
Debug.DrawRay(mainCamera.transform.position, mainCamera.transform.forward, Color.red);
RaycastHit hit;
if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hit, 1f)) {
if (Input.GetMouseButtonDown(0) && hit.transform.gameObject.GetComponent<Interactable>() != null) {
// interact with object
}
}
}
I want to be able to have one function that will take take of all the logic with my Interactable gameobjects. For example, a light switch would look like this:
public class LightSwitch : Interactable {
public void InteractWith() {
// logic
}
}
And a TV script like:
public class Television : Interactable {
public void InteractWith() {
// logic
}
}
Is there something I can put in the player script that can call the same method "InteractWith" on multiple scripts, Television, LightSwitch, Radio, etc...?
Answer by SlowCircuit · Jan 25, 2019 at 08:24 AM
In the Interactable class you make a public virtual void InteractWith() function.
In each class that inherits from Interactable (LightSwitch, Television, etc) you have a public override void InteractWith() function.
In the player code for interactions, get the Interactable component and called InteractWith(). It will call the child's version rather than the parent class, Interactable.
If there is code that should happen for all interactables, you can put that code in Interactable's version of InteractWith(). Then in each child's version, make sure to include base.InteractWith() so that it also calls the parent's version of the function.