I am creating a game in unity but im getting the error:
error CS0029: Cannot implicitly convert type ‘int’ to ‘string’.
Does anyone know the awnser?
public Text text;
int max;
int min;
int guess;
void Start () {
text.text = ("Pick a number in your head between " + min);
text.text = + max;
text.text = (" , but dont tell me!");
max = 1000;
min = 1;
guess = 500;
}
Uwe Keim
39k56 gold badges175 silver badges289 bronze badges
asked Jan 8, 2017 at 12:32
7
Try this:
public Text text;
int max;
int min;
int guess;
void Start () {
max = 1000;
min = 1;
guess = 500;
text.text = ("Pick a number in your head between " + min.ToString());
text.text += max.ToString();
text.text += (" , but dont tell me!");
}
But there is a better and more optimized way to concatenate strings, try this:
public Text text;
int max;
int min;
int guess;
void Start () {
max = 1000;
min = 1;
guess = 500;
text.text = string.Format("Pick a number in your head between {0} and {1}, but dont tell me!", min.ToString(), max.ToString());
}
answered Jan 8, 2017 at 12:40
0
Содержание
- error CS0029: Cannot implicitly convert type `UnityEngine.Transform’ to `UnityEngine.Vector3′
- 2 Ответов
- Ваш Ответ
- Welcome to Unity Answers
- Подписаться на вопрос
error CS0029: Cannot implicitly convert type `UnityEngine.Transform’ to `UnityEngine.Vector3′
using UnityEngine; using System.Collections; using FSM;
> i created a fsm context that gets the transform and sets it as the direction. what i am trying to do get my character to move on its own the error i am having is converting it. also i am not sure if the way i am doing it will work. t$$anonymous$$s is in my context——
public Transform gettransform() < return Controller.transform; >public void setcontroller(Transform pos) < pos = Controller.transform;
>
2 Ответов
Ответ от Julien-Lynge · 08/03/12 22:17
I’m sorry, I couldn’t read your code (you didn’t format it nicely). However, just glancing at it, your problem is that a Transform is not a Vector3. A transform is all the position, rotation, scaling, etc. information for an object. Instead of using Vector3 whatever = transform;, you likely need to use Vector3 whatever = transform.position;
transform.position is the position of the object, and is a Vector3. Likewise, transform.scale is a Vector3, and transform.rotation is a quaternion.
Ответ от mpavlinsky · 08/03/12 22:20
I don’t know anyt$$anonymous$$ng at all about FSM but it seems like you should be doing
Ваш Ответ
Welcome to Unity Answers
If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.
Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.
Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.
Подписаться на вопрос
Ответы Ответы и комментарии
6 пользователей подписаны.
Источник
Search Issue Tracker
In Progress
In Progress in 4.0.X
Found in [Package]
4.0.0-pre.1
How to reproduce:
1. Open the user’s attached project
2. Observe the Console window
Expected result: No errors
Actual result: “error CS0029: error CS0029: Cannot implicitly convert type ‘uint[]’ to ‘int[]’“ errors appear
Reproducible with: 4.0.0-pre.1 (2022.2.0b4, 2022.2.0b10, 2023.1.0a14)
Not reproducible with: 3.2.0-pre.3 (2020.3.40f1, 2021.3.11f1, 2022.1.20f1, 2022.2.0b10, 2023.1.0a14), 4.0.0-pre.1 (2022.1.20f1, 2022.2.0b3)
Reproduced on: macOS 12.4 (Intel)
Note: Deleting the Library folder doesn’t solve the issue
Full error: Library/PackageCache/com.unity.textmeshpro@4.0.0-pre.1/Scripts/Runtime/TMP_Text.cs(3427,35): error CS0029: Cannot implicitly convert type ‘uint[]’ to ‘int[]’
error CS0029. Как так??? |
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
Преобразование типов
Рассмоторим ситуацию, когда нам нужно преобразовать один тип данных в другой. К примеру, мы получили строку, в которой записано число и нам нужно умножить данное число на 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
и наоборот.
В следующей главе мы рассмотрим тему логические выражения.
I’m having an error produced when I compile my Unity game:
Error CS0029: Cannot implicitly convert type ‘Fruits[]’ to ‘Fruits’ (CS0029) (Assembly-CSharp)
It’s coming from the line:
f = Instantiate (fruitPrefab).GetComponents<Fruits>();
Why do I have this error and how can I resolve it?
Here is the rest of the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
private const float REQUIED_SLICEFORCE=400.0f;
private List<Fruits> fruties = new List<Fruits> ();
public GameObject fruitPrefab;
private float lastSpawn;
private float deltaSpawn=2.0f;
public Transform trail;
private Collider2D[] fruitCols;
private Vector3 lastmousepos;
// Use this for initialization
private void Start () {
fruitCols=new Collider2D[0];
}
private Fruits GetFruits ()
{
Fruits f = fruties.Find (x=>!x.IsActive);
if (f==null)
{
f = Instantiate (fruitPrefab).GetComponents<Fruits>();
fruties.Add (f);
}
return f;
}
}