- Home /
Why is this giving me an error? (ToBuiltin problems)
I'm not quite sure what's happening here. I'm getting the error "InvalidCastException: Cannot cast from source type to destination type." However, I can't see anything wrong. Here is the code:
var locX : float = 5; var locY : float = 5; var sizeX : int = 60; var sizeY : int = 40; var buttonText : String; var pieceToCreate : GameObject; var positionToSpawn : Vector3 = Vector3(-3,0,0);
// Save variables var builtInSaveArrayX : int[]; var builtInSaveArrayY : int[]; var builtInSaveArrayZ : int[]; var isSaveButton : boolean = false; private var saveItem : Transform;
function OnGUI () { // Declare Skin
if (GUI.Button (Rect ( (Screen.width*(locX/10)) - (sizeX / 2), (Screen.height*(locY/10)), sizeX, sizeY), buttonText))
{
if(!isSaveButton)
Instantiate(pieceToCreate, positionToSpawn, transform.rotation);
else
saveIt();
}
}
function saveIt() { var userObject : GameObject[] = GameObject.FindGameObjectsWithTag("moveable"); var closest : GameObject; var closestDist = Mathf.Infinity;
var saveArrayX : Array = new Array();
var saveArrayY : Array = new Array();
var saveArrayZ : Array = new Array();
var itemsOnScreen : int;
for (saveItem in userObject)
{
itemsOnScreen++;
// Augment array and store pos. data
saveArrayX.length = itemsOnScreen-1;
saveArrayY.length = itemsOnScreen-1;
saveArrayZ.length = itemsOnScreen-1;
saveArrayX[itemsOnScreen-1] = saveItem.transform.position.x;
saveArrayY[itemsOnScreen-1] = saveItem.transform.position.y;
saveArrayZ[itemsOnScreen-1] = saveItem.transform.position.z;
}
builtInSaveArrayX = saveArrayX.ToBuiltin(int);
// builtInSaveArrayY = saveArrayY.ToBuiltin(int); // builtInSaveArrayZ = saveArrayZ.ToBuiltin(int);
if (!PlayerPrefsX.SetIntArray("savedLevel1_xValues", builtInSaveArrayX))
{
Debug.Log("oops, the gameobject array saving failed terribly");
}
if (!PlayerPrefsX.SetIntArray("savedLevel1_yValues", builtInSaveArrayY))
{
Debug.Log("oops, the gameobject array saving failed terribly");
}
if (!PlayerPrefsX.SetIntArray("savedLevel1_zValues", builtInSaveArrayZ))
{
Debug.Log("oops, the gameobject array saving failed terribly");
}
Debug.Log("Total items " + itemsOnScreen + " Size of array " + saveArrayX.length);
Debug.Log("Positions " + saveArrayX);
}
Answer by Jessy · Jan 13, 2011 at 01:46 PM
saveItem.transform.position.whatever is a float. (Vector3s are 3 floats.)
If your values are going to be floating-point representations of integers, you can convert each one to an int using parseInt(//float goes here), or one of these Mathf functions. Also, there's no reason to use Arrays anymore. Use Lists, and then you have ConvertAll available to you.
Your answer
Follow this Question
Related Questions
assigning arrays with for in 1 Answer
For In Loop Fills all values in arrays problem 2 Answers
Saving Array Objects in Android. 0 Answers
Convert class of int vars into an array 0 Answers
PlayerPrefsX plugin error when build for windows store 3 Answers