Hello,
I'm making some sample projects and hobby games to learn this and that, and while making object placement using raycasting I've bumped into some issues I just can't figure out.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuilderVisuals : MonoBehaviour {
public float length = 3;
public GameObject placeHolder;
public GameObject blockToPlace;
GameObject visual;
void Start() {
visual = Instantiate(placeHolder, transform.position, transform.rotation);
visual.SetActive(false);
}
void FixedUpdate() {
RaycastHit hit;
Ray buildingRay = new Ray(this.transform.position, this.transform.forward);
//Debug.DrawRay(this.transform.position, this.transform.forward * length);
if (Physics.Raycast(buildingRay, out hit, length)) {
Debug.Log("ray successful");
if (hit.transform.gameObject.tag == "Block") {
Debug.Log("'block' tag indentified");
visual.SetActive(true);
visual.transform.position = hit.transform.position + hit.normal;
if (Input.GetButtonDown("Build")) {
Instantiate(blockToPlace, visual.transform.position, visual.transform.rotation);
}
if (Input.GetButtonDown("Hit")) {
Destroy(hit.transform.gameObject);
}
} else {
visual.SetActive(false);
}
}
}
}
First, I check if the raycasting hits anything at all, if yes, check if the hit object has the tag "Block", and if yes, run the desired code.
This is pretty simple even for me, but according to the included debug lines, rays are doing it's job just fine, but the tag check rarely evaluates to true.
This script is attached to the Unity Standard Assets FPSController's camera object. If I'm standing still, it never works, and rarely when moving. The rays are fine, but the tag check just doesn't work. The whole level is just a bunch of initialized cubes in a grid, all of them tagged up as needed.
Also I'm not sure if I'm checking against the first object the ray hit, but according to [this][1] it should be okay.
The whole project&level seems like the first alpha minecraft, a small cubic world where you can replace blocks, but in dx12.
[imgur link][2]
Any help would be appreciated!
[1]: https://answers.unity.com/questions/384355/stopping-a-raycast-after-hit.html
[2]: https://imgur.com/a/j1eFI17
↧