Item Collection with Raycast / C#
Dear Community,
After watching several tutorials and study the Unity Libraries, my c# script still won't work correctly. My C# Knowledge isn't that big yet, so this script might be pretty easy to understand for people with C# experience here :)
The goal is it, to create a script that allows the player to collect an item only by looking at it (in the range of 5.0f) and pressing a key (for example "e").
Did i miss something?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemRaycast : MonoBehaviour
{
public GameObject Item;
public GameObject PickupText;
public RaycastHit Hit;
private void Start()
{
PickupText = this.gameObject.transform.GetChild(0).GetChild(0).gameObject;
}
// Update is called once per frame
void Update()
{
var fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, transform.forward, out Hit, 5.0f) && Hit.collider.gameObject.tag == "Item")
{
//Show item name
PickupText.SetActive(true);
if (Input.GetKeyDown("e"))
{
//Do Something
Destroy(this.gameObject);
}
}
}
}
Good day.
did you debugged the code? IS the raycast hiting it? Is the "if " beeing executed?
Try to find what line is what is not doing what you expect to do.
Bye!
Answer by Toharawk · Jan 24, 2019 at 05:21 PM
@tormentoarmagedoom Thanks for your time, your reply is really appreciated. It seems like this question has been posted twice accidentally. Anyway, unfortunately thescript still is not working correctly. I still dont get the Pickup Text to active. Also, ive noticed that in the line 21 the var fwd is not included. Looks like it is more an logic issue. Any Idea how i can get the result (Line 24+) working? Best, Toha
You must debug your code while running, line by line, watching the values of all variables, checking all comparations to see whichone is not beeing true. Then focus on that variables to see why is not true.
I never use raycasts so I can not see only by reading iif there is some logic problem.
But as all "if". some condition is not doing what you expect. You need to find wich.