"int to float" conversion when I cannot find one

I have been confused for about the past half hour trying to solve this. On line 22, I receive the error “Cannot implicitly convert type float' to int’. An explicit conversion exists” ; when, from what I understand, the MathF.Round() converts float to nearest int. I have only been using Unity3D for the past 5 days, which is also the length of time I have been able to learn C#(which is kinda learn as I need- horrible but fastest way)

using UnityEngine;
using System.Collections;

public class UpgradeManager : MonoBehaviour {

    public Main main;

    public string Name;
    public int WaterRisk;
    public int FoodRisk;
    public int FeulRisk;
    public int MaleRisk;
    public int FemaleRisk;
    public int SuccessChance;
    public int FoodIncrease;
    public int WaterIncrease;
    public int FeulIncrease;
    public float Owned;

    private void CM(int Resource){
        float NR = Resource;
        Resource = Mathf.Round ((NR * Mathf.Pow (Owned, 1.5f)));
        return Resource;
    }

    public void ClickedUpgrade(){
        WaterRisk = CM (WaterRisk);
        FeulRisk = CM (FeulRisk);
        FoodRisk = CM (FoodRisk);
        SuccessChance -= CM (Owned);
        WaterIncrease = CM (WaterIncrease);
        FoodIncrease = CM (FoodIncrease);
        FeulIncrease = CM (FeulIncrease);

        int RandChance = Random.Range (1, SuccessChance + 1);
        if (RandChance <= SuccessChance) {
            main.WaterCanHold += WaterIncrease;
            main.FoodCanHold += FoodIncrease;
            main.FeulCanHold += FeulIncrease;
            Owned += 1;
        } else {
            main.TotalWater -= Random.Range (WaterRisk/2, WaterRisk + 1);
            main.TotalFood -= Random.Range (FoodRisk/2, FoodRisk +1);
            main.TotalFeul -= Random.Range (FeulRisk/2, FeulRisk +1);
        }
    }

    void Update(){

    }
}

it returns a float. So you need to cast your return values to an int to assign them to “Resource”.

Resource = (int)Mathf.Round((NR *Mathf.Pow(Owned, 1.5f)));

1 Like

An explicit conversion exists. Why not use that?

myFloat = (float)myInt;
myInt = (int)myFloat;
15 Likes

Strategos, I figured that mathf.Round() also converted to int since it rounds to nearest int. But that does make sense. Thank you, gotta keep that one memorised.

BoredMormon, is that fir converting an int into float and vice versa? (have not seen/used that before)

It’s called casting. It’s worth learning, you will use it a lot.

1 Like

Mathf.Round() rounds, but returns a float. If you need an int, use Mathf.RoundToInt().

ITS WORTH LEARNING. I SOLVED MY PROBLEM WITH THIS THANKS !

This was spot on! Fixed a fillAmount problem for me! :slight_smile: Thumbs Up!

1 Like