Error cs0029 cannot implicitly convert type float to bool

using UnityEngine; using System.Collections; public class RightMovement : MonoBehaviour { public float maxSpeed = 10f; bool facingRight = true; void Start() {} void FixedUpdate(...

Input.GetAxis("Horizontal") > 0 is a Boolean (true/false) value which will be true if the return value from GetAxis is greater than zero, or false otherwise. That’s why it’s complaining about trying to shoehorn a Boolean into a float variable.

It sounds like you want to force it to be non-negative only, in which case there are two likely possibilities.


The first is to ensure that negative values are translated to zero and that would involve something like:

float move = Input.GetAxis("Horizontal");
if (move < 0) move = 0;

or, if you’re the sort that prefers one-liners:

float move = Math.Max(0, Input.GetAxis("Horizontal"));

The second would be to translate negative to the equivalent positive, something like:

float move = Input.GetAxis("Horizontal");
if (move < 0) move = -move;

or, again, a one-liner:

float move = Math.Abs(Input.GetAxis("Horizontal"));

I suspect the former is probably what you’re after but you should think about what you want negative values turned in to, and adjust to that.

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



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

public class PlayerShoot : MonoBehaviour
{
    public PlayerController PlayerController;
    public Camera camera;

    public float damage;

    public float canShoot = true;
    WaitForSeconds shootDelay = new WaitForSeconds(0.2f);

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Shoot();
    }

    void Shoot()
    {
        if (Input.GetMouseButtonDown(0))
        {
            PlayerController.animator.SetBool("Shoot", true);
        }

        if (Input.GetMouseButtonUp(0))
        {
            PlayerController.animator.SetBool("Shoot", false);
        }

        if (Input.GetMouseButton(0) && canShoot) 
        {
            StartCoroutine(ShootDelayCoroutine());
            RaycastHit hit;
            if (Physics.Raycast(camera.transform.position, camera.transform.forward, out hit))
            {
                print("Enemy Takes Damage : " + hit.collider.gameObject.name);
                if (hit.collider.GetComponent())
                {
                    hit.collider.GetComponent().TakeDamage(damage);
                }
            }
        }

        IEnumerator ShootDelayCoroutine()
        {
            canShoot = false;
            yield return shootDelay;
            canShoot = true;
        }
    }
}

What I have tried:

<pre>how to fix error CS0029: Cannot implicitly convert type 'bool' to 'float' and  error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'float'

I’m still learning and hope you can help me with my problem?

  • Remove From My Forums
  • Question

  • User-390775641 posted

    Hello:

    I’m coming from C++ and the following is bugging me. Say, I have the code:

    public enum MyEnum
    {
    	ME_VALUE1 = 0x1,
    	ME_VALUE2 = 0x2,
    	ME_VALUE3 = 0x4,
    }
    MyEnum v = MyEnum.ME_VALUE1 | MyEnum.ME_VALUE3;
    if(v & MyEnum.ME_VALUE1)  //This line gives an error
    {
    	//Do something
    }
    
    
    
    
    That line where I do 'if' gives me the following 
    "error CS0029: Cannot implicitly convert type '<classname>.Graph.MyEnum' to 'bool'".

    Well it is clear that I'm trying it not to be 0. Is there any way to enable this in Settings?

Answers

  • User596829554 posted

    You may want to read through this article. It does a great job outlining the gotcha’s when converting from C++ to C#.

    http://msdn.microsoft.com/en-us/magazine/cc301520.aspx

    I think you’re falling into two of these traps one is a more managed environment that C# is and the other is

    Reference and Value Types (taken from above link)

          C# distinguishes between value types and reference types. Simple types (int, long, double, and so on) and structs are value types, while all classes are reference types, as are Objects. Value types hold their value on the stack,
    like variables in C++, unless they are embedded within a reference type. Reference type variables sit on the stack, but they hold the address of an object on the heap, much like pointers in C++. Value types are passed to methods by value (a copy is made),
    while reference types are effectively passed by reference.

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

Ошибка Unity CS0029: невозможно неявно преобразовать тип float в bool. РЕШЕНО …

Я пытаюсь сравнить переменную с плавающей запятой со значением ключа словаря. Но я получаю сообщение об ошибке, что его нельзя преобразовать из float в bool. Значение словаря — это целое число без знака, которое я использовал как число с плавающей точкой.

 void RunAnimation() { float aloop = (float)AnimationLoop[CurrentAnimation]; if(frame%aloop) { } } 

Это вызывает ошибку в операторе if: «Невозможно неявно преобразовать тип ‘float’ в ‘bool’». Но оба значения явно плавают, я не понимаю, как выходит что-то еще.

  • 2 Чего вы ожидаете if(frame%aloop) делать? Проблема в этой строке.
  • вау, я понял это в тот момент, когда перезагрузил страницу. Я забыл добавить == значение. Простите за тупой вопрос.

Вы можете сделать это на C / C ++, но не на C #. Вам нужно написать это:

if ((frame % aloop) != 0) 

В C / C ++ a bool на самом деле просто числовое значение, которое либо 0 (ложь), либо другое значение (истина). В твоем случае, frame % aloop было бы «допустимым bool» в C / C ++.

C #, с другой стороны, действительно ожидает bool выражение, однако frame % aloop оценивается как числовой тип. Таким образом ошибка.

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

Tweet

Share

Link

Plus

Send

Send

Pin

error CS0029. Как так???

nanaminer Дата: Вторник, 16 Мая 2017, 12:50 | Сообщение # 1

частый гость

Сейчас нет на сайте

Здравствуйте!
У меня есть ассет PuppetMaster, я хочу обратится к одному из скриптов, но Unity не понимает, тип переменной из скрипта к которому я хочу обратиться и пишет мне:
error CS0029: Cannot implicitly convert type `int’ to `RootMotion.Dynamics.Weight’ crazy т.е. Unity не понимает, что Puppet.GetComponent<BehaviourPuppet> ().collisionResistance это int. Как объяснить это Unity?
Помогите пожалуйста, Зарание спасибо!
Вот мой код:

Код

using UnityEngine;
using System.Collections;
using RootMotion.Dynamics;
using RootMotion;
using RootMotion.Demos;

public class Puppet : MonoBehaviour {

public GameObject Puppet;

void Start(){
Puppet.GetComponent<BehaviourPuppet> ().collisionResistance = 0;
}
}

Vostrugin Дата: Вторник, 16 Мая 2017, 14:01 | Сообщение # 2

постоянный участник

Сейчас нет на сайте

Судя по всему это Вы не понимаете, а не Unity. Поле collisionResistance имеет тип Weight, о чём и говорит ошибка.




EchoIT Дата: Вторник, 16 Мая 2017, 18:23 | Сообщение # 3

старожил

Сейчас нет на сайте

nanaminer, ты сейчас берёшь и удаляешь все ассеты, затем выкачиваешь справку по C# и Unity Scripting API на комп, а затем на месяц себе отрубаешь интернет, и работаешь, используя только эту информацию. Исключительно только после этого можешь продолжать заниматься геймдевом.


Долгожданный анонсик: State of War

nanaminer Дата: Среда, 17 Мая 2017, 14:09 | Сообщение # 4

частый гость

Сейчас нет на сайте

Здравствуйте, спасибо за отклик.

Небольшая выдержка из скрипта к которому я обращаюсь:

Код

[TooltipAttribute(«Smaller value means more unpinning from collisions (multiplier).»)]
   /// <summary>
   /// Smaller value means more unpinning from collisions (multiplier).
   /// </summary>
   public float collisionResistance;

Т.е. эта переменная float.
(как float я тоже пытался обращаться — та-же ошибка)
Как так? %)

Storm54 Дата: Четверг, 18 Мая 2017, 09:56 | Сообщение # 5

постоянный участник

Сейчас нет на сайте

Вроде ошибка совсем в другом месте. Например, класса RootMotion я не вижу
nanaminer Дата: Пятница, 19 Мая 2017, 18:26 | Сообщение # 6

частый гость

Сейчас нет на сайте

Здравствуйте.

Цитата Storm54 ()

класса RootMotion я не вижу

Не видите где? В скрипте с объявлением переменной только выдержка, весь скрипт огромный, но там есть этот класс.

seaman Дата: Пятница, 19 Мая 2017, 22:55 | Сообщение # 7

старожил

Сейчас нет на сайте

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

Код

using RootMotion.Dynamics;
using RootMotion;
using RootMotion.Demos;

Может достаточно одного RootMotion? Может у них (хотя конечно маловероятно) повторяются определения в разных namespace?

nanaminer Дата: Понедельник, 22 Мая 2017, 14:50 | Сообщение # 8

частый гость

Сейчас нет на сайте

Здравствуйте!
Спасибо всем, кто помогал, сегодня нашёл решение:

Код

Puppet.GetComponent<BehaviourPuppet> ().collisionResistance.floatValue = 0;

нужно было добавить, что изменяю именно floatValue ^_^ .

seaman Дата: Понедельник, 22 Мая 2017, 18:08 | Сообщение # 9

старожил

Сейчас нет на сайте

Тогда от чего же вы писали:

Цитата

public float collisionResistance;
Т.е. эта переменная float.

Вводили нас в заблуждение?
Вам с самого начала говорили, что «Поле collisionResistance имеет тип Weight»

Сообщение отредактировал seamanПонедельник, 22 Мая 2017, 18:08

Понравилась статья? Поделить с друзьями:
  • 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
  • Error cs0019 operator cannot be applied to operands of type double and double