Creating a Player Action Button

Hello everyone. Recently started using Unity again after a long hiatus. I am looking to create a script that will give the player the ability to press the “E” key to active a button for things like opening a door, trap door, or anything else (in this one I would like for it to give the player the ability to jump but that is for another time, need to get the button to work properly first). I have gone through tutorials and read through the documentation but I may be missing something here. Here is what I have so far:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FirstPersonPlayer : MonoBehaviour
{
public Camera camera;

void Update()
{
if (Input.GetKeyDown(“E”))
{
//Raycast
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, out hit))
{
GameObject objectHit = hit.transform.gameObject;
//Try getting ActionObject Component from the retrieved object
ActionObject actionObj = objectHit.getComponent();
if (actionObj != null)
{
//if ActionObject is found call DoAction()
actionObj.DoAction();
}
}
}
}

}

During the step “ActionObject actionObj = objectHit.getComponent();” I get an error saying that the GameObject does not contain a definition for getComponent. Not sure what I am missing here.

Thanks

Did you check the online docs for the .GetComponent method?

https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html

Capitalization is very important in C# identifiers and many other places in programming: capitalize your G.

Also, please review the first post in the forum for how to format your code properly.

1 Like

Sorry about that. Will do. Wow, that was a dumb mistake. I will keep reviewing the documentation. I was overthinking it. Thank you for the reply.

1 Like