Was having trouble understanding and getting my building system from before to work, so I’ve started trying to write it a different way. No clue if it will end up working or not, but it’ll be a valuable learning experience.
In my raycast I want to check if the collider’s tag is equal to “something” (in this instance “Foundation_SnapPoint”) and if so, move the instantiated object to the position of the collider. Looking at the old scripts, I thought what I have might work, but it isn’t an I’m not sure how to go about it. Any help would be appreciated.
Edit: The Foundation_SnapPoint is a child of the foundation. Just thought to check the transform on the SnapPoint and noticed the position is 1, 0, 0, which makes sense as it is exactly one foundation over from the actual foundation. I could see that being a problem, however, the object isn’t moving it’s position to 1,0,0 worldspace or anything when the raycast hits the SnapPoint, so I’m still at a loss there. Sorry if this is confusing, kind of confusing myself. lol
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuildingSystem : MonoBehaviour
{
public GameObject foundation;
private GameObject previewGameObject = null;
public bool isBuilding;
public LayerMask layer;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
NewBuilding(foundation);
}
if (isBuilding)
{
CastBuildRay();
}
}
private void CastBuildRay()
{
Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 25f, layer))
{
Debug.Log(hit.collider.name);
if (previewGameObject == foundation && hit.collider.tag == "Foundation_SnapPoint")
{
previewGameObject.transform.position = hit.collider.transform.position;
}
else
{
//Use 3 lines below for primitives
float y = hit.point.y + (previewGameObject.transform.localScale.y / 2f);
Vector3 pos = new Vector3(hit.point.x, y, hit.point.z);
previewGameObject.transform.position = pos;
//previewGameObject.transform.position = hit.point; //use this if importing properly anchored models
}
}
else
{
var pos = ray.origin + ray.direction * 25f;
previewGameObject.transform.position = pos;
}
}
public void NewBuilding(GameObject _go)
{
var lookPos = Camera.main.transform.position + Camera.main.transform.forward * 25f;
previewGameObject = Instantiate(_go, lookPos, Quaternion.identity);
isBuilding = true;
}
}