Задача:
Бросить луч из центра камеры и на месте соприкосновения с объектом создать сферу.
Скрипт:
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);
}
}
Проблема: сфера не отображается.
Проход дебагером:
{
.............
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;
.....................
}
Почему так происходит? Магия? Компилятор Unity? JIT?
Как решить проблему?
P.S. Скрипт присоединен к камере.
Персонаж реализован, как в книге Unity In Action. P.P.S. Если убрать переменную eif (Physics.Raycast(ray, out hit) )
SphereIndicator(hit.point);
Если убрать переменную е, то debuger просто проверяет условие и ведет себя, как будто оно равно false.
Метод SphereIndicator не вызывается.