Error cs0029 cannot implicitly convert type string to unityengine ui text

I just decided to try Unity. And i have problem. Can someone expain me whats wrong? : using UnityEngine; using System.Collections; using UnityEngine.UI; public class Game : MonoBehaviour { public

I just decided to try Unity. And i have problem. Can someone expain me whats wrong? :

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Game : MonoBehaviour
{
public Text summ;
public Buttons shopbtn = new Buttons;

void Start()
{
    shopbtn.btntext="Example";
    Debug.Log(shopbtn.btntext);
}}
_________________________________________________
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Buttons : MonoBehaviour 
{
public Text btntext;
}

Just one simple example. Why it does not work?

error CS0029: Cannot implicitly convert type string to `UnityEngine.UI.Text’

But when btntext is situated in Game class it works.

Ehsan Sajjad's user avatar

Ehsan Sajjad

61.4k16 gold badges103 silver badges160 bronze badges

asked Aug 11, 2017 at 21:39

Dmitry's user avatar

1

You need to set the text property of the Text instance:

shopbtn.btntext.text="Example";

Currently you have a field of type Text and you are trying to assign a string to it, hence the error.

answered Aug 11, 2017 at 21:46

Owen Pauling's user avatar

Owen PaulingOwen Pauling

11k20 gold badges53 silver badges64 bronze badges

1

Did you try improved

shopbtn.btntext.Text = (UnityEngine.UI.Text)"Example";

Community's user avatar

answered Aug 11, 2017 at 21:43

Serge's user avatar

SergeSerge

313 bronze badges

See more:

THIS ERROR IS COMING .

AssetsStandard AssetsUtilitySimpleActivatorMenu.cs(38,31): error CS0029: Cannot implicitly convert type ‘string’ to ‘UnityEngine.UI.Text’

What I have tried:

THIS IS MY SCRIPT .

using UnityEngine;
using System.Collections;
using UnityEngine.UI;



#pragma warning disable 618
namespace UnityStandardAssets.utility
{
    public class SimpleActivatorMenu 
    {
        
        public Text camSwitchButton ;
        public GameObject[] objects;


        private int m_CurrentActiveObject;


        private void OnEnable(){
        
            // active object starts from first in array
            m_CurrentActiveObject = 0;
            camSwitchButton = objects[m_CurrentActiveObject].name;
        }


        public void NextCamera()
        {
            int nextactiveobject = m_CurrentActiveObject + 1 >= objects.Length ? 0 : m_CurrentActiveObject + 1;

            for (int i = 0; i < objects.Length; i++)
            {
                objects[i].SetActive(i == nextactiveobject);
            }

            m_CurrentActiveObject = nextactiveobject;
            camSwitchButton = objects[m_CurrentActiveObject].name;
             
             
        }
    }
}

Comments

Is this a third re-post of the same question?

Well it is almost the same. See my solution below.


Solution 1

Quote:

camSwitchButton = objects[m_CurrentActiveObject].name;

You are trying to store a string value in a variable which can only hold instances of the Text class. The compiler is (correctly) telling you that you can’t do that.

As we keep telling you, STOP guessing, and start reading the documentation or following a decent tutorial. Posting a new question here every time you try to shove the square peg in the round hole and fail is NOT a sensible way to learn how to write code.

Я следую руководству на YouTube, чтобы создать игру в Unity

Вот ссылка на видео, которое начнется там, где он напишет этот код Ссылка

Это просто текст, который появляется и исчезает, когда я вхожу в другую комнату, OnTriggerEnter2D вызывает StartCoroutine, если нужноText

Скриншот pic

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class RoomMove : MonoBehaviour
{
    public Vector2 cameraChange;
    public Vector3 playerChange;
    private CameraMovment cam;
    public bool needText;
    public GameObject text;
    public Text placeText;
    public string placeName;

    // Start is called before the first frame update
    void Start()
    {
        cam = Camera.main.GetComponent<CameraMovment>();

    }

    // Update is called once per frame
    void Update()
    {

    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.CompareTag("Player"))
        {
            cam.minPosition += cameraChange;
            cam.maxPosition += cameraChange;
            collision.transform.position += playerChange;

            if(needText)
            {
                StartCoroutine(placeNameCo);
            }
        }
    }
    private IEnumerator placeNameCo()
    {
        text.SetActive(true);
        placeText = placeName;
        yield return new WaitForSeconds(4f);
        text.SetActive(false);
    }
}

Я получаю 2 ошибки:

Error   CS1503  Argument 1: cannot convert from 'method group' to 'string'  Assembly-CSharp 

Error   CS0029  Cannot implicitly convert type 'string' to 'UnityEngine.UI.Text'    Assembly-CSharp 

1 ответ

Лучший ответ

placeText — это весь текстовый компонент, поэтому вы хотите назначить свою строку своему свойству text как:

placeText.text = placeName;


Кроме того, StartCoroutine требуется либо подпрограмма в параметре, либо строка. Поэтому замените строку 38 на:

StartCoroutine(placeNameCo()) или {{x1}}

Первый вариант предпочтительнее, потому что строковая версия имеет более высокие накладные расходы времени выполнения для запуска сопрограммы, и вы можете передать только один параметр.


0

Maarti
22 Дек 2019 в 06:20

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

koddchan

0 / 0 / 0

Регистрация: 29.08.2018

Сообщений: 1

1

29.08.2018, 17:36. Показов 6260. Ответов 2

Метки нет (Все метки)


Пишу Roblox Exploit (чит на игру)

делаю всё как на видео, почти

тут 2 одинаковых cs0029 ошибки

C#
1
2
3
4
5
       private void button8_Click(object sender, EventArgs e)
        {
            string script = richTextBox1; 
            api.SendScript(script);
        }

пользуюсь 2017 visual studio

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



910 / 795 / 329

Регистрация: 08.02.2014

Сообщений: 2,391

29.08.2018, 17:47

2

Лучший ответ Сообщение было отмечено koddchan как решение

Решение

1) по коду ошибки благополучно находится информация как её исправить
2) Вы присваиваете переменной типа string целый контрол richTextBox, что вы от этого ожидаете?
3) если Вам нужен текст что внутри richTextBox так и обращайтесь и получайте его в переменную string script = richTextBox1.Text;



1



Someone007

Эксперт .NET

6269 / 3897 / 1567

Регистрация: 09.05.2015

Сообщений: 9,188

29.08.2018, 17:47

3

Лучший ответ Сообщение было отмечено koddchan как решение

Решение

C#
1
string script = richTextBox1.Text;



1



Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error cs0029 cannot implicitly convert type float to bool
  • Error cs0021 cannot apply indexing with to an expression of type image
  • Error cs0019 operator cannot be applied to operands of type vector3 and vector3
  • Error cs0019 operator cannot be applied to operands of type vector3 and int
  • Error cs0019 operator cannot be applied to operands of type string and string

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии