M
M
Maxim2017-03-28 22:51:20
C++ / C#
Maxim, 2017-03-28 22:51:20

How to cast a beam in Unity?

Task:

Throw a beam from the center of the camera and create a sphere at the point of contact with the object.

Script:
using System;
using UnityEngine;
using System.Collections;

public class RayShooter : MonoBehaviour
{
    private Camera _camera;

    // Use this for initialization
    void Start ()
  {
      _camera = GetComponent<Camera>();
  }
  
  // Update is called once per frame
  void Update ()
    {
      if (Input.GetMouseButton(0))
      {
            var centerPoint = new Vector3(_camera.pixelWidth / 2, _camera.pixelHeight /2, 0);
          Ray ray = _camera.ScreenPointToRay(centerPoint);
          RaycastHit hit;
          bool e = Physics.Raycast(ray, out hit);
            if (e)
              SphereIndicator(hit.point);
      }
  }

    private IEnumerator SphereIndicator(Vector3 position)
    {
        GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        sphere.transform.position = position;

        Debug.Log("Sphere");
        yield return new WaitForSeconds(1);
        Destroy(sphere);
    }
}

Problem: The sphere is not displayed.
Debugger pass:
{
.............
  RaycastHit hit;
  bool e = Physics.Raycast(ray, out hit);  // e = true
  if (e) 
      SphereIndicator(hit.point);  // Запуск метода   
}

private IEnumerator SphereIndicator(Vector3 position)
{ // Дебагер тут

    GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); // А тут его нет. 
    //Он ушёл выполнять другие скрипты.

    sphere.transform.position = position;
.....................
}

Why is this happening? Magic? Unity compiler? JIT?
How to solve the problem?
PS The script is attached to the camera.
The character is implemented as in the Unity In Action book.
ddcb2550b31d4331a850ed3b47f3a8ed.PNG
f0552d3102194b8c9e4d2dd2a8a19fbc.PNG
542aa20416c24ed1ad4130e68c5d9ba2.PNG

PPS If we remove the variable e
if (Physics.Raycast(ray, out hit) ) 
      SphereIndicator(hit.point);

Если убрать переменную е, то debuger просто проверяет условие и ведет себя, как будто оно равно false.
Метод SphereIndicator не вызывается.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2017-03-28
@Got_Oxidus

SphereIndicator is a coroutine, and coroutines are started with StartCoroutine :

void Update ()
{
    if (Input.GetMouseButton(0))
    {
        var centerPoint = new Vector3(_camera.pixelWidth / 2, _camera.pixelHeight /2, 0);
        Ray ray = _camera.ScreenPointToRay(centerPoint);
        RaycastHit hit;
        bool e = Physics.Raycast(ray, out hit);
        if (e)
        {
            StartCoroutine(SphereIndicator(hit.point));
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question