I get the error on:
lad = GameObject.FindGameObjectsWithTag ("Ladder");
I’m just trying to disable all the ladders in the scene while the alarm is on and then enable them again once the alarm goes away. I’m not sure what the error means but need it fixed as soon as possible. I’m using C# and Unity 5.
Thanks for any help you guys can provide!
using UnityEngine;
using System.Collections;
public class LevelAlarm : MonoBehaviour {
public bool alarmOn = false;
public bool bPlayerHidden = false;
// How long an alarm lasts for
[SerializeField]
private float alarmTimer = 5.0f;
private float alarmCurrentTimer = 0.0f;
public GameObject lad;
// Use this for initialization
void Start ()
{
lad = GameObject.FindGameObjectsWithTag ("Ladder");
}
// Update is called once per frame
void Update ()
{
// While alarm is on, run a timer
if (alarmOn)
{
alarmCurrentTimer += Time.deltaTime;
lad.SetActive(false);
// Timer is complete, alarm resets
if(alarmCurrentTimer >= alarmTimer)
{
alarmOn = false;
alarmCurrentTimer = 0.0f;
lad.SetActive(true);
}
}
}
}
Backs
24.1k5 gold badges55 silver badges81 bronze badges
asked Aug 26, 2015 at 11:19
0
GameObject.FindGameObjectsWithTag() returns an array of GameObjects, if you want first object of this array, use this:
void Start ()
{
var objects = GameObject.FindGameObjectsWithTag ("Ladder");
if(objects != null && objects.Length > 0)
{
lad = objects[0];
}
}
answered Aug 26, 2015 at 11:23
Taher RahgooyTaher Rahgooy
6,4683 gold badges19 silver badges30 bronze badges
It’s GameObject.FindGameObjectWithTag, not GameObject.FindGameObjectsWithTag, don’t has character «s» after «Object».
dhilmathy
2,7822 gold badges20 silver badges29 bronze badges
answered Jul 26, 2018 at 9:42
Error CS0029: Cannot implicitly convert type UnityEngine.GameObject[]' toUnityEngine.GameObject’
This error simply means that you try to stop alarm whose tag are «Ladder».It creates an array and the function you use accept only one element of utilityEngine.GameObject. So you may use foreach loop to access all elements in the array by using :
public bool alarmOn = false;
public bool bPlayerHidden = false;
// How long an alarm lasts for
[SerializeField]
private float alarmTimer = 5.0f;
private float alarmCurrentTimer = 0.0f;
**public GameObject[] lad;**
// Use this for initialization
void Start ()
{
lad = GameObject.FindGameObjectsWithTag ("Ladder");
}
// Update is called once per frame
void Update ()
{
// While alarm is on, run a timer
if (alarmOn)
{
alarmCurrentTimer += Time.deltaTime;
**foreach(var eachLad in lad)
{
eachLad.SetActive(false);
}**
// Timer is complete, alarm resets
if(alarmCurrentTimer >= alarmTimer)
{
alarmOn = false;
alarmCurrentTimer = 0.0f;
**foreach(var eachLad in lad)
{
eachLad.SetActive(true);
}**
}
}
}
answered Aug 26, 2015 at 11:39
Amit guptaAmit gupta
1071 silver badge3 bronze badges
I get the error on:
lad = GameObject.FindGameObjectsWithTag ("Ladder");
I’m just trying to disable all the ladders in the scene while the alarm is on and then enable them again once the alarm goes away. I’m not sure what the error means but need it fixed as soon as possible. I’m using C# and Unity 5.
Thanks for any help you guys can provide!
using UnityEngine;
using System.Collections;
public class LevelAlarm : MonoBehaviour {
public bool alarmOn = false;
public bool bPlayerHidden = false;
// How long an alarm lasts for
[SerializeField]
private float alarmTimer = 5.0f;
private float alarmCurrentTimer = 0.0f;
public GameObject lad;
// Use this for initialization
void Start ()
{
lad = GameObject.FindGameObjectsWithTag ("Ladder");
}
// Update is called once per frame
void Update ()
{
// While alarm is on, run a timer
if (alarmOn)
{
alarmCurrentTimer += Time.deltaTime;
lad.SetActive(false);
// Timer is complete, alarm resets
if(alarmCurrentTimer >= alarmTimer)
{
alarmOn = false;
alarmCurrentTimer = 0.0f;
lad.SetActive(true);
}
}
}
}
Backs
24.1k5 gold badges55 silver badges81 bronze badges
asked Aug 26, 2015 at 11:19
0
GameObject.FindGameObjectsWithTag() returns an array of GameObjects, if you want first object of this array, use this:
void Start ()
{
var objects = GameObject.FindGameObjectsWithTag ("Ladder");
if(objects != null && objects.Length > 0)
{
lad = objects[0];
}
}
answered Aug 26, 2015 at 11:23
Taher RahgooyTaher Rahgooy
6,4683 gold badges19 silver badges30 bronze badges
It’s GameObject.FindGameObjectWithTag, not GameObject.FindGameObjectsWithTag, don’t has character «s» after «Object».
dhilmathy
2,7822 gold badges20 silver badges29 bronze badges
answered Jul 26, 2018 at 9:42
Error CS0029: Cannot implicitly convert type UnityEngine.GameObject[]' toUnityEngine.GameObject’
This error simply means that you try to stop alarm whose tag are «Ladder».It creates an array and the function you use accept only one element of utilityEngine.GameObject. So you may use foreach loop to access all elements in the array by using :
public bool alarmOn = false;
public bool bPlayerHidden = false;
// How long an alarm lasts for
[SerializeField]
private float alarmTimer = 5.0f;
private float alarmCurrentTimer = 0.0f;
**public GameObject[] lad;**
// Use this for initialization
void Start ()
{
lad = GameObject.FindGameObjectsWithTag ("Ladder");
}
// Update is called once per frame
void Update ()
{
// While alarm is on, run a timer
if (alarmOn)
{
alarmCurrentTimer += Time.deltaTime;
**foreach(var eachLad in lad)
{
eachLad.SetActive(false);
}**
// Timer is complete, alarm resets
if(alarmCurrentTimer >= alarmTimer)
{
alarmOn = false;
alarmCurrentTimer = 0.0f;
**foreach(var eachLad in lad)
{
eachLad.SetActive(true);
}**
}
}
}
answered Aug 26, 2015 at 11:39
Amit guptaAmit gupta
1071 silver badge3 bronze badges
Преобразование типов
Рассмоторим ситуацию, когда нам нужно преобразовать один тип данных в другой. К примеру, мы получили строку, в которой записано число и нам нужно умножить данное число на 2.
Пример:
using System;
public class Program
{
static void Main(string[] args)
{
string input = "1234";
int a = input * 2; // error CS0029
}
}
Из-за того, что язык программирования C# является строго типизированным, сделать это на прямую не получиться, сперва нам нужно преобразовать один тип данных в другой. Именно этой теме будет посвящена данная глава.
Тема преобразований типов данных довольно большая, так что в этой главе мы разберем решения проблем, которые встречаются чаще всего, а точнее преобразование строк и чисел. В будущих частях книги мы разберем данную тему подробнее.
Преобразование числа в строку
Рассмотрим ситуацию, когда у нас есть некоторая переменная int a, значение которой мы получили извне, не важно откуда предположим, что теперь a = 3. И у нас появилась задача, как сделать так, чтобы некоторая строка string output, равнялась значению из переменной a.
Как это будет выглядеть в коде:
using System;
public class Program
{
static void Main(string[] args)
{
int a = 3;
string output = a; // error CS0029
}
}
Такая ошибка вызвана из-за того, что C# является строго типизированным языком.
Для того, что решить данную задачу, нам потребуется преобразовать тип данных int в тип данных string, делать мы это будет при помощи метода ToString(), который присущ всем типам данным.
Пример:
using System;
public class Program
{
static void Main(string[] args)
{
string output = "";
int a = 3;
output = a.ToString();
float b = 3.5f;
output = b.ToString();
char c = 'a';
output = c.ToString();
}
}
Последний пример очень важен, так как у нас есть понимание того, что тип данных string состоит из символов (char), но при этом string не может быть равен char без преобразования.
Преобразование строки в число
Рассмотрим другую ситуацию, когда у нас есть некоторая строка string input, в которую мы положили значение, опять же не важно откуда, предположим напрямую string input = "256". Мы на 100% уверены, что в этой строке содержатся только цифры. Перед нами стоит задача возвести данное число в квадрат (умножить число само на себя 2 раза). Без преобразования у нас будет похожая ошибка, что и в примере выше.
Пример:
using System;
public class Program
{
static void Main(string[] args)
{
string input = "256";
int a = input * input; // error CS0029
}
}
Чтобы преобразовать число в строку нам потребуется вызвать метод int.Parse() и в скобках указать значения типа string.
Пример:
using System;
public class Program
{
static void Main(string[] args)
{
string input = "256";
int a = int.Parse(input) * int.Parse(input);
}
}
int.Parse() — метод, который принимает на вход строку и преобразует ее в тип данных int.
Так же мы можем использовать: float.Parse(). Метод так же должен получить строку, только после выполнения вернет уже тип данных float.
Пример:
using System;
public class Program
{
static void Main(string[] args)
{
string input = "256,4";
float a = float.Parse(input) * float.Parse(input);
}
}
Заключение
Таким образом, теперь мы поняли как преобразовывать тип данных int в string и наоборот.
В следующей главе мы рассмотрим тему логические выражения.
| description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
|---|---|---|---|---|---|
|
Compiler Error CS0029 |
Compiler Error CS0029 |
07/20/2015 |
CS0029 |
CS0029 |
63c3e574-1868-4a9e-923e-dcd9f38bce88 |
Compiler Error CS0029
Cannot implicitly convert type ‘type’ to ‘type’
The compiler requires an explicit conversion. For example, you may need to cast an r-value to be the same type as an l-value. Or, you must provide conversion routines to support certain operator overloads.
Conversions must occur when assigning a variable of one type to a variable of a different type. When making an assignment between variables of different types, the compiler must convert the type on the right-hand side of the assignment operator to the type on the left-hand side of the assignment operator. Take the following the code:
int i = 50; long lng = 100; i = lng;
i = lng; makes an assignment, but the data types of the variables on the left and right-hand side of the assignment operator don’t match. Before making the assignment the compiler is implicitly converting the variable lng, which is of type long, to an int. This is implicit because no code explicitly instructed the compiler to perform this conversion. The problem with this code is that this is considered a narrowing conversion, and the compiler does not allow implicit narrowing conversions because there could be a potential loss of data.
A narrowing conversion exists when converting to a data type that occupies less storage space in memory than the data type we are converting from. For example, converting a long to an int would be considered a narrowing conversion. A long occupies 8 bytes of memory while an int occupies 4 bytes. To see how data loss can occur, consider the following sample:
int i = 50; long lng = 3147483647; i = lng;
The variable lng now contains a value that cannot be stored in the variable i because it is too large. If we were to convert this value to an int type we would be losing some of our data and the converted value would not be the same as the value before the conversion.
A widening conversion would be the opposite of a narrowing conversion. With widening conversions, we are converting to a data type that occupies more storage space in memory than the data type we are converting from. Here is an example of a widening conversion:
int i = 50; long lng = 100; lng = i;
Notice the difference between this code sample and the first. This time the variable lng is on the left-hand side of the assignment operator, so it is the target of our assignment. Before the assignment can be made, the compiler must implicitly convert the variable i, which is of type int, to type long. This is a widening conversion since we are converting from a type that occupies 4 bytes of memory (an int) to a type that occupies 8 bytes of memory (a long). Implicit widening conversions are allowed because there is no potential loss of data. Any value that can be stored in an int can also be stored in a long.
We know that implicit narrowing conversions are not allowed, so to be able to compile this code we need to explicitly convert the data type. Explicit conversions are done using casting. Casting is the term used in C# to describe converting one data type to another. To get the code to compile we would need to use the following syntax:
int i = 50; long lng = 100; i = (int) lng; // Cast to int.
The third line of code tells the compiler to explicitly convert the variable lng, which is of type long, to an int before making the assignment. Remember that with a narrowing conversion, there is a potential loss of data. Narrowing conversions should be used with caution and even though the code will compile you may get unexpected results at run-time.
This discussion has only been for value types. When working with value types you work directly with the data stored in the variable. However, .NET also has reference types. When working with reference types you are working with a reference to a variable, not the actual data. Examples of reference types would be classes, interfaces and arrays. You cannot implicitly or explicitly convert one reference type to another unless the compiler allows the specific conversion or the appropriate conversion operators are implemented.
The following sample generates CS0029:
// CS0029.cs public class MyInt { private int x = 0; // Uncomment this conversion routine to resolve CS0029. /* public static implicit operator int(MyInt i) { return i.x; } */ public static void Main() { var myInt = new MyInt(); int i = myInt; // CS0029 } }
See also
- User-defined conversion operators
|
Dodeca 0 / 0 / 0 Регистрация: 16.08.2020 Сообщений: 2 |
||||
|
1 |
||||
|
16.08.2020, 14:14. Показов 1795. Ответов 2 Метки unity (Все метки)
Помогите пожалуйста понять/решить ошибку! Компилятор ругается на 14 строку, искал решение в интернете, но не смог решить.
__________________
0 |
|
epyskop 143 / 130 / 30 Регистрация: 26.07.2017 Сообщений: 633 |
||||
|
16.08.2020, 14:53 |
2 |
|||
|
Transform большой — там и rotation и scale обьекта.
0 |
|
3088 / 1617 / 921 Регистрация: 26.10.2018 Сообщений: 4,620 |
|
|
16.08.2020, 14:55 |
3 |
|
Ну так ты определись, target это у тебя вектор и трансформ?
0 |
