Casting Int To Float Doesn't Work

Trying to change the value of a variable by dividing one int by another. The first is cast to a float with (float). See code below.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SysRand = System.Random;
public class HangmanObject : MonoBehaviour {
    Controller controllerScript;
    HangmanScript hangmanScript;
    public int count;
    public double randomNumber;
    public float currentNumber;
    public int now;
    public string currentWord;
    public float time;
    // Use this for initialization
    void Start () {
        controllerScript = GameObject.FindGameObjectWithTag("Player").GetComponent<Controller>();
        hangmanScript = GameObject.FindGameObjectWithTag("Player").GetComponent<HangmanScript>();
        SysRand hangmanRand = controllerScript.myRand;
        randomNumber = hangmanRand.NextDouble();
        time = (this.gameObject.transform.position.x/50f);
        Invoke("PickWord", time);
    }
 
 // Update is called once per frame
 void Update () {
    }
    void PickWord()
    {
        for(int i = 0; i < hangmanScript.currentList.Count; i++)
        {
            now = i + 1;
            currentNumber = (float)now / hangmanScript.currentList.Count;
            if(randomNumber < currentNumber)
            {
                currentWord = hangmanScript.currentList[i];
            }
        }
    }
}

The variable “now” is cast to a float, so the float variable currentNumber should return a float (and a number less than 1). It doesn’t - it returns an int (0 for every iteration until the final, where it returns 1).

Any suggestions?

Sorry, I can’t see anything that’s wrong to help you out. But the part you’re describing is accurate and returning a float for me.

This just in: I’m kind of a moron!

I wanted to exit the loop when it was first successful. So all I needed was “break;” after the currentWord assignment.

Nothing to see here…:sweat_smile:

Might sticky this post and lock it so no changes can be made, a grim warning until the end of time. Not really.

3 Likes

:slight_smile:

1 Like