简体   繁体   中英

C# unity Changing a variable using ray cast hit information

The camera in this game has a target that can be changed by clicking on the other models and will then be the cameras focus, the script below is what I got so far however every time I click on an object in game the target just says none rather than any of the models.

Ray toMouse = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
bool didHit = Physics.Raycast(toMouse, out hitInfo);

if (didHit)
{
    if (hitInfo.collider.tag == "Cell" && Input.GetMouseButtonDown(0))
    {
        Debug.Log("Cell hit");

        target = hitInfo.transform.Find(gameObject.name);       
    }
}

If this script is on the camera, something like this should do it:

GameObject target;
// or
Transform target;

void Update()
{
    if(Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit))
        {
            target = hit.transform.gameObject;
            // or
            target = hit.transform;
        }
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM