- Home /
Problems with transform.parent in unity 4.6
So i have been working with unity 4.6 since it has the UI new stuff and when beta stopped and there was a stable version (no beta), so i was making menus and everything was fine, but when i wanted to make my own inventory, i tried to put the slots (prefabs) to the parent (a panel) and it doesnt work because of this:
Setting the parent of transform which resides in a prefab is disabled to prevent data corruption.
so anything to fix it? and also say "k does not exist in the current context" so here is my code.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Inventory : MonoBehaviour {
public GameObject slots;
int x = -110;
int y = 110;
void Start () {
for(int i = 1; i < 6; i++);
{
for(int k = 1; k < 6; k++);
{
GameObject slot = (GameObject)Instantiate(slots);
slots.transform.parent = this.gameObject.transform;
slot.name - "Slot" + 1 + "." + k;
slot.GetComponent<RectTransform>().localPosition = new Vector3(x, y, 0);
x = x + 55;
//Right here i get the k does not exist in the current context
if(k == 4)
{
x = -100;
y = y - 55;
}
}
}
}
}
Answer by LukaKotar · Feb 05, 2015 at 02:57 AM
Line 18, you're referring to the prefab reference ( slots
) rather than the new instantiated object ( slot
).
Edit: You're closing the for
loops with a semicolon ( ;
).
//Incorrect:
for(int i = 1; i < 6; i++); //The semicolon closes the statement
{
//Code here is outside of the loop, and will only run once.
//Since the 'i' variable is part of the loop, it cannot be accessed from here.
}
//Correct:
for(int i = 1; i < 6; i++)
{
//Code here will execute until 'i' is equal to 6
}
Here's what your code should look like:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Inventory : MonoBehaviour {
public GameObject slots;
int x = -110;
int y = 110;
void Start () {
for(int i = 1; i < 6; i++)
{
for(int k = 1; k < 6; k++)
{
GameObject slot = (GameObject)Instantiate(slots);
slot.transform.parent = transform;
slot.name - "Slot" + 1 + "." + k;
slot.GetComponent<RectTransform>().localPosition = new Vector3(x, y, 0);
x = x + 55;
if(k == 4)
{
x = -100;
y = y - 55;
}
}
}
}
}
didnt worked out, still having the k does not exist in the current context
Answer by VOTRUBEC · Feb 06, 2015 at 03:40 AM
On line 19, instead of :
slot.name - "Slot" + 1 + "." + k;
might you be trying to do:
slot.name = "Slot" + i.ToString() + "." + k.ToString();