@AsTrOZeD
Зверь

Не могу решить ошибки в скрипте для unity. Как их решить?

Делаю 2D игру websketches.ru/blog/2d-igra-na-unity-podrobnoye-ru... (отсюда взял скрипт для бесконечного фона)
Остановился на RendererExtensions
Скрипт с этого сайта устаревший, поэтому стал искать "свежий". Нашел более новый, но все равно есть ошибки. Исправил больше половины, оставшиеся не смог.

Вот скрипт(мной измененный,где остается 5 ошибок)
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

/// <summary>
/// Parallax scrolling script that should be assigned to a layer
/// </summary>
public class Scrolling : MonoBehaviour
{

    public float timeLeft = 5.0f;
    /// <summary>
    /// Scrolling speed
    /// </summary>
    public Vector2 speed = new Vector2(10, 10);

    /// <summary>
    /// Moving direction
    /// </summary>
    public Vector2 direction = new Vector2(-1, 0);

    /// <summary>
    /// Movement should be applied to camera
    /// </summary>
    public bool isLinkedToCamera = false;

    /// <summary>
    /// 1 - Background is infinite
    /// </summary>
    public bool isLooping = false;

    /// <summary>
    /// 2 - List of children with a renderer.
    /// </summary>
    private List<Transform> backgroundPart;

    // 3 - Get all the children
    void Start()
    {
        // For infinite background only
        if (isLooping)
        {
            // Get all the children of the layer with a renderer
            backgroundPart = new List<Transform>();

            for (int i = 0; i < transform.childCount; i++)
            {
                Transform child = transform.GetChild(i);

                // Add only the visible children
                if(child.GetComponent<Renderer>() != null)
                {
                    backgroundPart.Add(child);
                }
            }

            // Sort by position.
            // Note: Get the children from left to right.
            // We would need to add a few conditions to handle
            // all the possible scrolling directions.
            backgroundPart = backgroundPart.OrderBy(
                t => t.position.x
                ).ToList();
        }
    }

    void Update()
    {

        //Timer
        timeLeft -= Time .deltaTime ;

        if (timeLeft <= 0.0f)
        {
            speed.x += 100;
            speed.y += 100;
        }


        // Movement
        Vector3 movement = new Vector3(
            speed.x * direction.x,
            speed.y * direction.y,
            0);

        movement *= Time.deltaTime;
        transform.Translate(movement);

        // Move the camera
        if (isLinkedToCamera)
        {
            Camera.main.transform.Translate(movement);
        }

        // 4 - Loop
        if (isLooping)
        {
            // Get the first object.
            // The list is ordered from left (x position) to right.
            Transform firstChild = backgroundPart.FirstOrDefault();

            if (firstChild != null)
            {
                // Check if the child is already (partly) before the camera.
                // We test the position first because the IsVisibleFrom
                // method is a bit heavier to execute.
                if (firstChild.position.x < Camera.main.transform.position.x)
                {
                    // If the child is already on the left of the camera,
                    // we test if it's completely outside and needs to be
                    // recycled.
                    if (firstChild.GetComponent<Renderer>().IsVisibleFrom(Camera.main) == false)
                    {
                        // Get the last child position.
                        Transform lastChild = backgroundPart.LastOrDefault();
                        Vector3 lastPosition = lastChild.transform.position;
                        Vector3 lastSize = (lastChild.renderer.bounds.max - lastChild.renderer.bounds.min);

                        // Set the position of the recyled one to be AFTER
                        // the last child.
                        // Note: Only work for horizontal scrolling currently.
                        firstChild.position = new Vector3(lastPosition.x + lastSize.x, firstChild.position.y, firstChild.position.z);

                        // Set the recycled child to the last position
                        // of the backgroundPart list.
                        backgroundPart.Remove(firstChild);
                        backgroundPart.Add(firstChild);
                    }
                }
            }
        }
    }
}

Вот ошибки
5bfea905b8fe0018969044.png
Знаю что в новом unity многое изменили, но я новичок так, что не знаю, что поменяли или убрали.
  • Вопрос задан
  • 796 просмотров
Решения вопроса 3
GavriKos
@GavriKos Куратор тега Unity
Или добавьте екстеншн, или перепишите код как написано тут:
wiki.unity3d.com/index.php/IsVisibleFrom
Ответ написан
@nock36
В websketches.ru НАПУТАЛИ с переводом. Расширять класс нужно как раз таки в файле - “RendererExtensions.cs”
т.е. прописать это:

using UnityEngine;

public static class RendererExtensions
{
public static bool IsVisibleFrom(this Renderer renderer, Camera camera)
{
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera);
return GeometryUtility.TestPlanesAABB(planes, renderer.bounds);
}
}

вот ссылка на оригинальный вариант туториала: ссылка
ДАЛЕЕ можно воспользоваться их скриптом "ScrollingScript.cs" в котором нужно исправить ошибки такие:
не - firstChild.renderer.IsVisibleFrom(Camera.main) ,
а - firstChild.GetComponent().IsVisibleFrom(Camera.main) (на 07.02.19)
Ответ написан
MrMureno
@MrMureno Куратор тега Unity
VR for all
с первой ошибкой вам помогает GavriKos

а про renderer
у вас наверно юнити новее и нельзя брать (как в старых версиях) по такой сокращенной ссылке компонент.
// так нельзя)
lastChild.renderer
// а вот так сработает
lastChild.GetComponent<Renderer>()
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы