Ошибка юнити cs0619

Помогите решить проблему кто знает как. Ошибка CS0619, незнаю что делать.

AssetsStandard AssetsUtilitySimpleActivatorMenu.cs(10,16): error CS0619: 'GUIText' is obsolete: 'GUIText has been removed. Use UI.Text instead.'

введите сюда описание изображения

  • c#
  • unity3d

aepot's user avatar

aepot

45.3k5 золотых знаков22 серебряных знака51 бронзовый знак

задан 7 авг 2020 в 7:04

Sanchek19's user avatar

Sanchek19Sanchek19

231 серебряный знак6 бронзовых знаков

5

  • Приведите ошибку и условия её возникновения в текстовом виде в вопросе

    7 авг 2020 в 7:04

  • AssetsStandard AssetsUtilitySimpleActivatorMenu.cs(10,16): error CS0619: ‘GUIText’ is obsolete: ‘GUIText has been removed. Use UI.Text instead.’

    7 авг 2020 в 7:13

  • попробуй использовать вместо GUI.Text UI.Text

    7 авг 2020 в 8:22

  • Как это сделать ?

    7 авг 2020 в 8:43

  • Добавьте фрагмент неработающей части кода в вопрос текстом, и вам подскажут, как поправить

    7 авг 2020 в 10:57

2 ответа

Написано же что устарела GUITexture и GUITex используйте UI.Image и UI.Image.Text

ответ дан 7 авг 2020 в 7:26

Aziz Umarov's user avatar

Aziz UmarovAziz Umarov

22.4k2 золотых знака10 серебряных знаков32 бронзовых знака

Сначала подключи UnityEngine.UI и замени где GUIText на Text

ответ дан 26 янв 2021 в 2:55

Daniel Petukhov's user avatar

Содержание

  1. 【Unity】The way to fix error CS0619:’GUIText’ is obsolete:’GUIText has been removed. Use UI.Text instead.’
  2. Overview
  3. Environment
  4. Occurences
  5. The way to fix it
  6. AssetsStandard AssetsUtilitySimpleActivatorMenu.cs(11,16): error CS0246: The type or namespace name ‘UI’ could not be found (are you missing a using directive or an assembly reference?)

【Unity】The way to fix error CS0619:’GUIText’ is obsolete:’GUIText has been removed. Use UI.Text instead.’

Table of Contents

Overview

There occured error CS0619:’GUIText’ is obsolete:’GUIText has been removed. Use UI.Text instead.’ to use Standard Assets. This article shows a way to fix it.

Environment

Occurences

Making C# script from Assets > Create > C# Script .

Attaching the script to Sphere object by drag & drop, I get message ‘Can’t add script’ .

This massage warns that the name of the script is different from its class name or there are some error of compiling. But I don’t find any error for compiling or the difference of the names.

Now, finding these GUIText error in console tab.

The way to fix it

Double-clicking the error in the console tab then the script “SimpleActivatiorMenu.cs” is opended.

Change it like following.

Addition : using UnityEngine.UI;
Comment out : public GUIText camSwitchButton;
Addition : public Text camSwitchButton;

This is a sample code fixed.

After changing codes and save it, the script can be attached to the Sphere Objects.

Источник

AssetsStandard AssetsUtilitySimpleActivatorMenu.cs(11,16): error CS0246: The type or namespace name ‘UI’ could not be found (are you missing a using directive or an assembly reference?)

So I am getting t$$anonymous$$s error:

AssetsStandard AssetsUtilitySimpleActivatorMenu.cs(11,16): error CS0246: The type or namespace name ‘UI’ could not be found (are you missing a using directive or an assembly reference?)

When I googled it, I ended up referred to t$$anonymous$$s article:

w$$anonymous$$ch recommends adding:

to SimpleActivatorMenu.cs and ForcedReset.cs

It also links to t$$anonymous$$s article:

So I follow those steps, as listed there, and when I attempt to test run, the following error appears:

PlayerSettings Validation: Requested build target group (20) doesn’t exist; #define symbols for scripting won’t be added. UnityEditor.PlayerSettings:SetScriptingDefineSymbolsForGroup(BuildTargetGroup, String) UnityStandardAssets.CrossPlatformInput.Inspector.CrossPlatformInitialize:SetEnabled(String, Boolean, Boolean) (at Assets/Standard Assets/Editor/CrossPlatformInput/CrossPlatformInputInitialize.cs:127) UnityStandardAssets.CrossPlatformInput.Inspector.CrossPlatformInitialize:.cctor() (at Assets/Standard Assets/Editor/CrossPlatformInput/CrossPlatformInputInitialize.cs:22) UnityEditor.EditorAssemblies:ProcessInitializeOnLoadAttributes(Type[])

I should also note that t$$anonymous$$s happened after I upgraded to 2019.3.0f6 and imported the Standard Assets from the Unity Store.

Источник

Ошибка в скрипте

Ошибка в скрипте

Всем привет, юнька выдает ошибку:
Assets/Project_OneGame/Player/moveCam.cs(31,13): error CS0619: `UnityEngine.Component.rigidbody’ is obsolete: `Property rigidbody has been deprecated. Use GetComponent<Rigidbody>() instead. (UnityUpgradable)’

Подскажите… как можно это исправить?

Используется csharp

using UnityEngine;
using System.Collections;

public class CamMove : MonoBehaviour
{
    public Transform target; //Объект за которым летаем(Наш персонаж)
    public float distance = 3.0f; //На каком ратоянии от него
    public float xSpeed = 125.0f; //Чуствительность по Х
    public float ySpeed = 50.0f; //Y Чуствительность
    public float targetHeight = 2.0f; //Высота относительно объекта
                                      //Минимальный и максимальный угол поворота Y инче камеру разверет, Дальше у нас будет простая функция для инвертации их в обратные числа
    public float yMinLimit = 40;
    public float yMaxLimit = 80;
    //Максимальное удаление и приближение камеры к персонажу, искорость.
    public float maxDistance = 10.0f;
    public float minDistance = 0.5f;
    public float zoomRote = 90.0f;

    private float x = 0.0f; //Угол поворота по Y?
    private float y = 0.0f; //Уго поворота по X?

    [AddComponentMenu(«Scripts/Mouse Orbit»)] //Добавляем в меню

    public void Start()
    {
        //переворачивам углы
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        if (rigidbody)
            rigidbody.freezeRotation = true; //Если камера столкнется с физ.объектомона остановиться
    }

    public void LateUpdate()
    {
        if (target)
        {//Если цель установлена(Персонаж)
         //Меняем углы согласно положению мыши
            x += Input.GetAxis(«Mouse X») * xSpeed * 0.02f;
            y -= Input.GetAxis(«Mouse Y») * ySpeed * 0.02f;
            //Меняем дистанция до персонажа.
            distance -= (Input.GetAxis(«Mouse ScrollWheel») * Time.deltaTime) * zoomRote * Mathf.Abs(distance);
            distance = Mathf.Clamp(distance, minDistance, maxDistance);

            y = ClampAngle(y, yMinLimit, yMaxLimit); //Вызыв самописной функции для ограничения углов поврот
            movePlayer.x = x;
            //Повернуть камеру согласно поченым данным
            Quaternion rotation = Quaternion.Euler(y, x, 0);
            transform.rotation = rotation;

            //Двигаем камеру и следим за персонажем
            Vector3 position = rotation * new Vector3(0.0f, targetHeight + 0.5f, distance) + target.position;
            transform.position = position;

            //Следуйщи код нужен что бы камера не проваливалась по ланшафт  
            RaycastHit hit;
            Vector3 trueTargetPosition = target.transform.position new Vector3(0, targetHeight, 0);
            if (Physics.Linecast(trueTargetPosition, transform.position, out hit))
            {
                float tempDistance = Vector3.Distance(trueTargetPosition, hit.point) 0.28f;
                position = target.position (rotation * Vector3.forward * tempDistance + new Vector3(0, targetHeight, 0));
                transform.position = position;
            }
        }

    }
    //Меняем значения углов
    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < 360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}

Так же вот еще скрипт,они работают вместе.
И такая ошибка:
Assets/Project_OneGame/Player/AnimatePlayer.cs(10,9): error CS0619: `UnityEngine.Component.animation’ is obsolete: `Property animation has been deprecated. Use GetComponent<Animation>() instead. (UnityUpgradable)’

Используется csharp

using UnityEngine;
using System.Collections;

public class AnimatePlayer : MonoBehaviour
{

    public void Start()
    {
        // Устанавливаем все клипы анимации в режим цикла
        animation.wrapMode = WrapMode.Loop;
        // Кроме следующих  
        animation[«Attack01»].wrapMode = WrapMode.Once;
        animation[«jump»].wrapMode = WrapMode.Once;
        animation[«Skill»].wrapMode = WrapMode.Once;
        //У них одиночное выполнение

        //Останавливаем выполнение анимаций.
        animation.Stop();
    }

    public void Update()
    {
        // На основе нажатой клавиши выполняем анимацию
        if (movePlayer.IsDrawWeapon == false) //Если оружие не вытащено
        {
            if (Input.GetAxis(«Vertical») > 0.0f) //Проверяем на изминениея позиции персонажа повертикали, если да
            {
                if (movePlayer.speed == movePlayer._speed * 2) //Проверяем скорость Передвижения персонажа,  
                {
                    animation.CrossFade(«Run00»); //Если зажата клавиша shift, значит грузим анимацию бега
                }
                else
                {
                    animation.CrossFade(«Walk»); //В противном случаее ходьбу
                }
            }
            else if (Input.GetAxis(«Vertical») < 0.0f) //Далее все по анологии
            {
                if (movePlayer.speed == movePlayer._speed * 2)
                {
                    animation.CrossFade(«B_Run00»); //бег назад
                }
                else
                {
                    animation.CrossFade(«B_Walk»); //ходьба назад
                }
            }
            else if (Input.GetAxis(«Horizontal») > 0.0f)
            {
                if (movePlayer.speed == movePlayer._speed * 2)
                {
                    animation.CrossFade(«R_Run00»); //бег в право
                }
                else
                {
                    animation.CrossFade(«R_Walk»); //Шагание в право
                }

            }
            else if (Input.GetAxis(«Horizontal») < 0.0f)
            {
                if (movePlayer.speed == movePlayer._speed * 2)
                {
                    animation.CrossFade(«L_Run00»); //лево
                }
                else
                {
                    animation.CrossFade(«L_Walk»); //лево
                }
            }
            else if (Input.GetKey(KeyCode.Space)) //если сделан прыжок
            {

                animation.Play(«Jump_NoBlade»); //Включаем анимацию прыжка
            }
            else
            {
                animation.CrossFade(«Idle»); //просто стоим
            }
        }
        else if (movePlayer.IsDrawWeapon == true) //если оружие вытащено
        {
            if (Input.GetAxis(«Vertical») > 0.0f)
            {
                animation.CrossFade(«Run»); //бег в перед
            }
            else if (Input.GetAxis(«Vertical») < 0.0f)
            {
                animation.CrossFade(«B_Run»); //назад  
            }
            else if (Input.GetAxis(«Horizontal») > 0.0f)
            {
                animation.CrossFade(«R_Run»); //в право
            }
            else if (Input.GetAxis(«Horizontal») < 0.0f)
            {
                animation.CrossFade(«L_Run»); //в лево
            }
            else if (Input.GetKey(KeyCode.Space))
            {
                animation.Play(«jump»); //Прыжок
            }
            else
            {
                animation.CrossFade(«AttackStandy»); //просто стоим
            }

            //Анимация атаки
            if (Input.GetMouseButton(0)) //Если нажать маус 1
                animation.CrossFade(«Attack01»); //Включаем анимацию атаки
            if (Input.GetMouseButton(1)) //Если нажать маус 2
                animation.CrossFade(«Skill»); //Включаем анимацию скила
        }
    }
}

Последний раз редактировалось Zilius 18 окт 2015, 12:09, всего редактировалось 2 раз(а).

Zilius
UNец
 
Сообщения: 12
Зарегистрирован: 06 май 2015, 16:56

Re: Ошибка в скрипте

Сообщение samana 17 окт 2015, 19:40

А что, ошибка резко появилась? Вообще этот скипт должен выдать другую ошибку, так как movePlayer не существует там.

Может дело в другом скрипте?

Аватара пользователя
samana
Адепт
 
Сообщения: 4733
Зарегистрирован: 21 фев 2015, 13:00
Откуда: Днепропетровск

Re: Ошибка в скрипте

Сообщение PREZRAK 17 окт 2015, 20:05

Мда, это как-то глупо: скрывать адрес скрипта (полную ошибку), при этом давая сам скрипт. P.s.: что-то зачастили люди так делать…
+1: Где ошибка-то?

Аватара пользователя
PREZRAK
Старожил
 
Сообщения: 653
Зарегистрирован: 30 май 2013, 12:41
  • Сайт

Re: Ошибка в скрипте

Сообщение Zilius 18 окт 2015, 12:04

Простите, поправил,вроде бы все написал.

Скрипт movePlayer работает и не выдает ошибок
Вот сам скрипт :

Используется csharp

using UnityEngine;
using System.Collections;

public class movePlayer : MonoBehaviour
{

    private GameObject player; //Переменна объекта персонажа с которым будем работать.

    public static int speed = 6; //Скорость перемещения персонажа. Запись public static обозначает что мы сможем обращаться к этой переменной из любого скрипта
    public static int _speed; //постоянная скорость перемещения персонажа
    public int rotation = 250; //Скорость пповорота персонажа
    public int jump = 3; //Высота прыжка

    public static bool IsDrawWeapon; //Двоичная переменная, которая будет отвечать достануто ли у нас оружие.  
    public static float x = 0.0f; //угол поворота персонажа по оси x
    void Start()
    {
        IsDrawWeapon = false; //По умолчанию оружие у нас спрятано.
        _speed = speed; //Задаем постоянное стандартное значение скорости персонажа
        player = (GameObject)this.gameObject; //Задаем что наш персонаж это объект на котором расположен скрипт
    }

    void Update()
    {
        if (IsDrawWeapon == true) //Если оружие вытащено
        {
            speed = _speed * 2; // Меняем скорость передвижени(я это сделал потому что, у этой моделки нету анимаций движения простым шагом с мечом. а понижать скорость анимации у бега получиться не красиво)
            if (Input.GetKey(KeyCode.W)) //Если нажать W
            {
                player.transform.position += player.transform.forward * speed * Time.deltaTime; //Перемещаем персонажа в перед, с заданой скорость. Time.deltaTime ставится для плавного перемещения персонажа, если этого не будет он будет двигаться рывками
            }
            if (Input.GetKey(KeyCode.S))
            {
                speed = _speed / 2; //При передвижениии назад снижаем скорость перемещения
                player.transform.position -= player.transform.forward * speed * Time.deltaTime; //Перемещаем назад
            }
            if (Input.GetKeyUp(KeyCode.S))
            {
                speed = _speed * 2; //Возвращаем cтандартное значение
            }
            if (Input.GetKey(KeyCode.A))
            {
                player.transform.position -= player.transform.right * speed * Time.deltaTime; //перемещаем в лево
            }
            if (Input.GetKey(KeyCode.D))
            {
                player.transform.position += player.transform.right * speed * Time.deltaTime; //перемещаем в право
            }
            if (Input.GetKey(KeyCode.Space))
            {
                player.transform.position += player.transform.up * jump * Time.deltaTime; //Прыгаем
            }

            if (Input.GetKey(KeyCode.Tab)) //При нажатии и на кнопку Tab
            {
                IsDrawWeapon = false; //Мы спрячем наше оружие.
            }
        }
        else if (IsDrawWeapon == false) //Если оружие не спрятано. |||||| Сделано разделение на движения в зависимости от того вытащено ли у нас оружие или нет, потому что персонаж будет перемещаться сразной скорость у меня в этих случаях, как я уже написал из за отсутсвия некоторых анимаций у модельки.  
        {
            speed = _speed;//Скорость в стандартное значение
            if (Input.GetKey(KeyCode.LeftShift)) //Если зажать левый Shift
            {
                speed = _speed * 2; //Увеличиваем скорость перемещения(бег)
            }
            if (Input.GetKeyUp(KeyCode.LeftShift)) //Если отпустить
            {
                speed = _speed; //Возвращаем стандартное значение
            }
            if (Input.GetKey(KeyCode.W)) //Если нажать W
            {
                player.transform.position += player.transform.forward * speed * Time.deltaTime; //Перемещаем персонажа в перед.
            }
            if (Input.GetKey(KeyCode.S))
            {
                speed = _speed / 2;
                player.transform.position -= player.transform.forward * speed * Time.deltaTime; //Перемещаем назад
            }
            if (Input.GetKeyUp(KeyCode.S))
            {
                speed = _speed; //Возвращаем cтандартное значение
            }
            if (Input.GetKey(KeyCode.A))
            {
                player.transform.position -= player.transform.right * speed * Time.deltaTime; //перемещаем в лево
            }
            if (Input.GetKey(KeyCode.D))
            {
                player.transform.position += player.transform.right * speed * Time.deltaTime; //перемещаем в право
            }
            if (Input.GetKey(KeyCode.Space))
            {
                player.transform.position += player.transform.up * jump * Time.deltaTime; //Прыгаем
            }
            if (Input.GetKey(KeyCode.Tab)) //при нажатии на кнопку таб
            {
                IsDrawWeapon = true; //Мы вытащим наше оружие
            }
        }

        //Поворачиваем персонажа. Так как наша переменная x глобальна, из скрипта камеры в неё будем записывать длину на сколько сместился указатель мыши и по оси X и относительно этого будет повернут наш персонаж
        Quaternion rotate = Quaternion.Euler(0, x, 0); //Создаем новую переменную типа Quaternion для задавания угла поворота
        player.transform.rotation = rotate; //Поворачиваем персонаж

    }
}

Zilius
UNец
 
Сообщения: 12
Зарегистрирован: 06 май 2015, 16:56

Re: Ошибка в скрипте

Сообщение xRemx 18 окт 2015, 12:32

Попробуйте написать так

Используется csharp

Rigidbody rd;

void Start(){
rd = GetComponent<Rigidbody>();

}

А после уже проверяйте все что хотели. Мне такой способ помог.

xRemx
UNIт
 
Сообщения: 77
Зарегистрирован: 01 окт 2015, 20:41

Re: Ошибка в скрипте

Сообщение Zilius 18 окт 2015, 19:34

xRemx писал(а):Попробуйте написать так

Используется csharp

Rigidbody rd;

void Start(){
rd = GetComponent<Rigidbody>();

}

А после уже проверяйте все что хотели. Мне такой способ помог.

Если вставить этот код в скрипт,то получается следующая ошибка :
Assets/Project_OneGame/Player/moveCam.cs(4,11): error CS0116: A namespace can only contain types and namespace declarations

Zilius
UNец
 
Сообщения: 12
Зарегистрирован: 06 май 2015, 16:56

Re: Ошибка в скрипте

Сообщение xRemx 18 окт 2015, 21:59

Можете скинуть весь код, после того как вставили мой?

xRemx
UNIт
 
Сообщения: 77
Зарегистрирован: 01 окт 2015, 20:41

Re: Ошибка в скрипте

Сообщение Zilius 18 окт 2015, 23:14

xRemx писал(а):Можете скинуть весь код, после того как вставили мой?

Вот этот код, если я правильно вставил ваш код

Используется csharp

using UnityEngine;
using System.Collections;

Rigidbody rd;

void Start()
{
    rd = GetComponent<Rigidbody>();

}

public class CamMove : MonoBehaviour
{
    public Transform target; //Объект за которым летаем(Наш персонаж)
    public float distance = 3.0f; //На каком ратоянии от него
    public float xSpeed = 125.0f; //Чуствительность по Х
    public float ySpeed = 50.0f; //Y Чуствительность
    public float targetHeight = 2.0f; //Высота относительно объекта
                                      //Минимальный и максимальный угол поворота Y инче камеру разверет, Дальше у нас будет простая функция для инвертации их в обратные числа
    public float yMinLimit = 40;
    public float yMaxLimit = 80;
    //Максимальное удаление и приближение камеры к персонажу, искорость.
    public float maxDistance = 10.0f;
    public float minDistance = 0.5f;
    public float zoomRote = 90.0f;

    private float x = 0.0f; //Угол поворота по Y?
    private float y = 0.0f; //Уго поворота по X?

    [AddComponentMenu(«Scripts/Mouse Orbit»)] //Добавляем в меню

    public void Start()
    {
        //переворачивам углы
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        if (rigidbody)
            rigidbody.freezeRotation = true; //Если камера столкнется с физ.объектомона остановиться
    }

    public void LateUpdate()
    {
        if (target)
        {//Если цель установлена(Персонаж)
         //Меняем углы согласно положению мыши
            x += Input.GetAxis(«Mouse X») * xSpeed * 0.02f;
            y -= Input.GetAxis(«Mouse Y») * ySpeed * 0.02f;
            //Меняем дистанция до персонажа.
            distance -= (Input.GetAxis(«Mouse ScrollWheel») * Time.deltaTime) * zoomRote * Mathf.Abs(distance);
            distance = Mathf.Clamp(distance, minDistance, maxDistance);

            y = ClampAngle(y, yMinLimit, yMaxLimit); //Вызыв самописной функции для ограничения углов поврот
            movePlayer.x = x;
            //Повернуть камеру согласно поченым данным
            Quaternion rotation = Quaternion.Euler(y, x, 0);
            transform.rotation = rotation;

            //Двигаем камеру и следим за персонажем
            Vector3 position = rotation * new Vector3(0.0f, targetHeight + 0.5f, distance) + target.position;
            transform.position = position;

            //Следуйщи код нужен что бы камера не проваливалась по ланшафт  
            RaycastHit hit;
            Vector3 trueTargetPosition = target.transform.position new Vector3(0, targetHeight, 0);
            if (Physics.Linecast(trueTargetPosition, transform.position, out hit))
            {
                float tempDistance = Vector3.Distance(trueTargetPosition, hit.point) 0.28f;
                position = target.position (rotation * Vector3.forward * tempDistance + new Vector3(0, targetHeight, 0));
                transform.position = position;
            }
        }

    }
    //Меняем значения углов
    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < 360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}

Zilius
UNец
 
Сообщения: 12
Зарегистрирован: 06 май 2015, 16:56

Re: Ошибка в скрипте

Сообщение netghost55 19 окт 2015, 00:11

не правильно вставили, этот кусок кода надо внести в класс

Используется csharp

Rigidbody rd;

void Start()
{
    rd = GetComponent<Rigidbody>();

}

а то у вас он написан выше объявления класса.

Аватара пользователя
netghost55
UNIт
 
Сообщения: 108
Зарегистрирован: 23 июн 2015, 12:23

Re: Ошибка в скрипте

Сообщение xRemx 19 окт 2015, 00:14

ну почти правильно) условие в методе Start я тоже заменил(там где rigidbody был). У вас вообще как с знанием С# и программирования вообще?

Используется csharp

using UnityEngine;
using System.Collections;

public class CamMove : MonoBehaviour
{
   Rigidbody rd;
    public Transform target; //Объект за которым летаем(Наш персонаж)
    public float distance = 3.0f; //На каком ратоянии от него
    public float xSpeed = 125.0f; //Чуствительность по Х
    public float ySpeed = 50.0f; //Y Чуствительность
    public float targetHeight = 2.0f; //Высота относительно объекта
                                      //Минимальный и максимальный угол поворота Y инче камеру разверет, Дальше у нас будет простая функция для инвертации их в обратные числа
    public float yMinLimit = 40;
    public float yMaxLimit = 80;
    //Максимальное удаление и приближение камеры к персонажу, искорость.
    public float maxDistance = 10.0f;
    public float minDistance = 0.5f;
    public float zoomRote = 90.0f;

    private float x = 0.0f; //Угол поворота по Y?
    private float y = 0.0f; //Уго поворота по X?

    [AddComponentMenu(«Scripts/Mouse Orbit»)] //Добавляем в меню

    public void Start()
    {
           rd = GetComponent<Rigidbody>();
        //переворачивам углы
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        if (rd)
            rd.freezeRotation = true; //Если камера столкнется с физ.объектомона остановиться
    }

    public void LateUpdate()
    {
        if (target)
        {//Если цель установлена(Персонаж)
         //Меняем углы согласно положению мыши
            x += Input.GetAxis(«Mouse X») * xSpeed * 0.02f;
            y -= Input.GetAxis(«Mouse Y») * ySpeed * 0.02f;
            //Меняем дистанция до персонажа.
            distance -= (Input.GetAxis(«Mouse ScrollWheel») * Time.deltaTime) * zoomRote * Mathf.Abs(distance);
            distance = Mathf.Clamp(distance, minDistance, maxDistance);

            y = ClampAngle(y, yMinLimit, yMaxLimit); //Вызыв самописной функции для ограничения углов поврот
            movePlayer.x = x;
            //Повернуть камеру согласно поченым данным
            Quaternion rotation = Quaternion.Euler(y, x, 0);
            transform.rotation = rotation;

            //Двигаем камеру и следим за персонажем
            Vector3 position = rotation * new Vector3(0.0f, targetHeight + 0.5f, distance) + target.position;
            transform.position = position;

            //Следуйщи код нужен что бы камера не проваливалась по ланшафт  
            RaycastHit hit;
            Vector3 trueTargetPosition = target.transform.position new Vector3(0, targetHeight, 0);
            if (Physics.Linecast(trueTargetPosition, transform.position, out hit))
            {
                float tempDistance = Vector3.Distance(trueTargetPosition, hit.point) 0.28f;
                position = target.position (rotation * Vector3.forward * tempDistance + new Vector3(0, targetHeight, 0));
                transform.position = position;
            }
        }

    }
    //Меняем значения углов
    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < 360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}

xRemx
UNIт
 
Сообщения: 77
Зарегистрирован: 01 окт 2015, 20:41

Re: Ошибка в скрипте

Сообщение Zilius 19 окт 2015, 15:06

xRemx писал(а):ну почти правильно) условие в методе Start я тоже заменил(там где rigidbody был). У вас вообще как с знанием С# и программирования вообще?

Используется csharp

using UnityEngine;
using System.Collections;

public class CamMove : MonoBehaviour
{
   Rigidbody rd;
    public Transform target; //Объект за которым летаем(Наш персонаж)
    public float distance = 3.0f; //На каком ратоянии от него
    public float xSpeed = 125.0f; //Чуствительность по Х
    public float ySpeed = 50.0f; //Y Чуствительность
    public float targetHeight = 2.0f; //Высота относительно объекта
                                      //Минимальный и максимальный угол поворота Y инче камеру разверет, Дальше у нас будет простая функция для инвертации их в обратные числа
    public float yMinLimit = 40;
    public float yMaxLimit = 80;
    //Максимальное удаление и приближение камеры к персонажу, искорость.
    public float maxDistance = 10.0f;
    public float minDistance = 0.5f;
    public float zoomRote = 90.0f;

    private float x = 0.0f; //Угол поворота по Y?
    private float y = 0.0f; //Уго поворота по X?

    [AddComponentMenu(«Scripts/Mouse Orbit»)] //Добавляем в меню

    public void Start()
    {
           rd = GetComponent<Rigidbody>();
        //переворачивам углы
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        if (rd)
            rd.freezeRotation = true; //Если камера столкнется с физ.объектомона остановиться
    }

    public void LateUpdate()
    {
        if (target)
        {//Если цель установлена(Персонаж)
         //Меняем углы согласно положению мыши
            x += Input.GetAxis(«Mouse X») * xSpeed * 0.02f;
            y -= Input.GetAxis(«Mouse Y») * ySpeed * 0.02f;
            //Меняем дистанция до персонажа.
            distance -= (Input.GetAxis(«Mouse ScrollWheel») * Time.deltaTime) * zoomRote * Mathf.Abs(distance);
            distance = Mathf.Clamp(distance, minDistance, maxDistance);

            y = ClampAngle(y, yMinLimit, yMaxLimit); //Вызыв самописной функции для ограничения углов поврот
            movePlayer.x = x;
            //Повернуть камеру согласно поченым данным
            Quaternion rotation = Quaternion.Euler(y, x, 0);
            transform.rotation = rotation;

            //Двигаем камеру и следим за персонажем
            Vector3 position = rotation * new Vector3(0.0f, targetHeight + 0.5f, distance) + target.position;
            transform.position = position;

            //Следуйщи код нужен что бы камера не проваливалась по ланшафт  
            RaycastHit hit;
            Vector3 trueTargetPosition = target.transform.position new Vector3(0, targetHeight, 0);
            if (Physics.Linecast(trueTargetPosition, transform.position, out hit))
            {
                float tempDistance = Vector3.Distance(trueTargetPosition, hit.point) 0.28f;
                position = target.position (rotation * Vector3.forward * tempDistance + new Vector3(0, targetHeight, 0));
                transform.position = position;
            }
        }

    }
    //Меняем значения углов
    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < 360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}

Спасибо вам большое, скрипт заработал(теперь попробую изменить следующий скрипт). Ну про язык программирования я немного читал, а так я больше игрок))) Решил немного занять себя «разработкой» своей игры(фанат серии игр о пост апокалипсисе),пока есть свободное время.

Zilius
UNец
 
Сообщения: 12
Зарегистрирован: 06 май 2015, 16:56

Re: Ошибка в скрипте

Сообщение xRemx 19 окт 2015, 18:04

Удачи в разработке)

xRemx
UNIт
 
Сообщения: 77
Зарегистрирован: 01 окт 2015, 20:41


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: Yandex [Bot] и гости: 17

This time, I’ll introduce about Tips for those who use ARCore provided by Google with Unity. If you were developing with CloudAnchors on Unity 2017, and upgrading to the latest Unity 2018.2 (as of October 2018), you will encounter the error of above screen shot.

“Assets/GoogleARCore/Examples/CloudAnchors/Scripts/CloudAnchorUIController.cs(85,62): error CS0619: `UnityEngine.Network’ is obsolete: `The legacy networking system has been removed in Unity 2018.2. Use Unity Multiplayer and NetworkIdentity instead.’ ”

(I think if possible, you should not do upgrading Unity during developing. It includes the possibility of various errors other than this. Especially when you use something like Asset. You might need time to investigate the Asset.)

I think you can find the cause of the error immediately, but it is the IP address acquisition part in the Start method of ‘CloudAnchorUIController.cs’.

[Cause of Error]

The point is that the ‘UnityEngine.Network’ class is no longer used in Unity 2018.2 as in the following Bag Fix.

Bug fixes:

Fixed ‘UnityEngine.Network’ is obsolete: The legacy networking system has been removed in Unity 2018.2. Use Unity Multiplayer and NetworkIdentity instead.’ in Unity 2018.2 and above.

[ URL:https://github.com/google-ar/arcore-unity-sdk/releases ]

[Error Solution]

Download the latest ‘ARCore SDK for Unity‘ from the following site and import it. The latest version when I downloaded is v1.5.0.

[ URL : https://github.com/google-ar/arcore-unity-sdk/releases ]

This error can be easily avoided with this.

And the following errors that occurred at the same time are also resolved by the same solution.

“Assets/GoogleARCore/Examples/CloudAnchors/Scripts/CloudAnchorUIController.cs(85,62): error CS0619: `UnityEngine.Network.player’ is obsolete: `The legacy networking system has been removed in Unity 2018.2. Use Unity Multiplayer and NetworkIdentity instead.’”

“Assets/GoogleARCore/Examples/CloudAnchors/Scripts/CloudAnchorUIController.cs(85,69): error CS0619: `UnityEngine.NetworkPlayer.ipAddress’ is obsolete: `The legacy networking system has been removed in Unity 2018.2. Use Unity Multiplayer and NetworkIdentity instead.’”

[Important Points]

  1. If you are directly editing standard script in ARCore, you should take backups beforehand. Don’t forget. It will be overwritten and will be gone.
  2. When importing the latest ARCore package, you should delete the ARCore package that was previously installed before importing. Otherwise, the following error occurs at build time.

Error: Duplicate file(s) in apk:

This was about how to resolve errors that occurred when upgrading to Unity 2018.2 when using ARCore.

[Original Japanese Site: http://blog.lab7.biz/archives/13196323.html]

Установил последнюю версию Unity. Загрузил из assetstore.unity3d.com Standard assets. При импортировании сразу в консоли появились две ошибки:

AssetsStandard AssetsUtilityForcedReset.cs(6,27): error CS0619: ‘GUITexture’ is obsolete: ‘GUITexture has been removed. Use UI.Image instead.’

AssetsStandard AssetsUtilitySimpleActivatorMenu.cs(10,16): error CS0619: ‘GUIText’ is obsolete: ‘GUIText has been removed. Use UI.Text instead.’

Скажите что это значит и что нужно сделать чтобы все заработало?

I’m having script errors. But first what I’m doing.

I’m making my text colorful, the system should look like this. Every second, new differet color. But I scripted the code and it shows errors. Like:

error CS0619: UnityEngine.Component.renderer' is obsolete:Property renderer has been deprecated. Use GetComponent() instead. (UnityUpgradable)’

error CS1061: Type UnityEngine.Component' does not contain a definition formaterial’ and no extension method material' of typeUnityEngine.Component’ could be found (are you missing a using directive or an assembly reference?)

Also the script is this.

using UnityEngine;
using System.Collections;

public class Colors : MonoBehaviour

{
    public float timer = 0.0f;

    void Start()
    {

    }


    void Update()
    {
        timer += Time.deltaTime;
        if (timer >= 2.0f)//change the float value here to change how long it takes to switch.
        {
        // pick a random color
            Color newColor = new Color(Random.value, Random.value, Random.value, 1.0f);
        // apply it on current object's material
            renderer.material.color = newColor;
            timer = 0;
        }
    }
}

asked Jun 11, 2016 at 13:52

blue0berry's user avatar

blue0berryblue0berry

371 silver badge13 bronze badges

1

You can no longer access renderer.material.color directly anymore starting from Unity 5 up. you must use GetComponent<Renderer>(); to get the component of the GameObject first, then you can access the material from the Renderer.

public float timer = 0.0f;
 Renderer rd;

 void Start()
 {
     rd = gameObject.GetComponent<Renderer>();
 }


 void Update()
 {
     timer += Time.deltaTime;
     if (timer >= 2.0f)//change the float value here to change how long it takes to switch.
     {
         // pick a random color
         Color newColor = new Color(Random.value, Random.value, Random.value, 1.0f);
         // apply it on current object's material
         rd.material.color = newColor;

         timer = 0;
     }
 }

answered Jun 11, 2016 at 14:01

Programmer's user avatar

ProgrammerProgrammer

121k22 gold badges234 silver badges324 bronze badges

7

Студворк — интернет-сервис помощи студентам

Всем доброго времени суток, столкнулся с ошибками компилятора, это обычное дело для стандартных ассетов юнити. Ошибки по SimpleActivatorMenu и Forced я исправил, но есть еще две ошибки, инфу про них в интернете найти не смог, так что надеюсь, что вы поможете. Вот ошибки:
AssetsStandard AssetsUtilityFPSCounter.cs(7,31): error CS0619: ‘GUIText’ is obsolete: ‘GUIText has been removed. Use UI.Text instead.’
AssetsStandard AssetsUtilityFPSCounter.cs(15,17): error CS0619: ‘GUIText’ is obsolete: ‘GUIText has been removed. Use UI.Text instead.’
Сам скрипт небольшой, если можете тыкните меня в место, которое нужно исправить)

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using UnityEngine;
using UnityEngine.UI;
 
namespace UnityStandardAssets.Utility
{
    [RequireComponent(typeof (GUIText))]
    public class FPSCounter : MonoBehaviour
    {
        const float fpsMeasurePeriod = 0.5f;
        private int m_FpsAccumulator = 0;
        private float m_FpsNextPeriod = 0;
        private int m_CurrentFps;
        const string display = "{0} FPS";
        private GUIText m_GuiText;
 
 
        private void Start()
        {
            m_FpsNextPeriod = Time.realtimeSinceStartup + fpsMeasurePeriod;
            m_GuiText = GetComponent<GUIText>();
        }
 
 
        private void Update()
        {
            // measure average frames per second
            m_FpsAccumulator++;
            if (Time.realtimeSinceStartup > m_FpsNextPeriod)
            {
                m_CurrentFps = (int) (m_FpsAccumulator/fpsMeasurePeriod);
                m_FpsAccumulator = 0;
                m_FpsNextPeriod += fpsMeasurePeriod;
                m_GuiText.text = string.Format(display, m_CurrentFps);
            }
        }
    }
}

Понравилась статья? Поделить с друзьями:
  • Ошибка юнита zabbix server service
  • Ошибка юнита smbd service
  • Ошибка яна непомнящего
  • Ошибка юнита nginx service
  • Ошибка языкового файла торрент