Reputation: 3
I am trying to instantiate a Prefab
and then make a Panel
the parent of it. but it gives me this error:
Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption (GameObject: 'TargetIcon').
UnityEngine.Transform:SetParent(Transform)
How can I get ride of this error?
Here are the details:
I have a panel in a canvas which serves as a minimap. I have a prefab to be instantiated and the panel should be made as parent to this prefab. this code is attached to my panel:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MapObject {
public Image icon {get; set;}
public GameObject owner { get; set; }
}
public class MiniMapController : MonoBehaviour
{
public Transform playerPos;
public Camera mapCamera;
public static List<MapObject> mapObjects = new List<MapObject>();
public static void RegisterMapObject(GameObject o, Image i)
{
Image image = Instantiate(i);
mapObjects.Add(new MapObject() { owner = o, icon = i });
}
void Start()
{
}
// Update is called once per frame
void Update()
{
DrawMapIcons();
}
void DrawMapIcons()
{
foreach(MapObject mo in mapObjects)
{
Vector3 screenPos = mapCamera.WorldToViewportPoint(mo.owner.transform.position);
mo.icon.transform.SetParent(this.transform);
screenPos.z = 0;
mo.icon.transform.position = screenPos;
}
}
}
and then this code is used to make a mapobject:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MakeMapObject : MonoBehaviour
{
[SerializeField]
public Image image;
void Start()
{
MiniMapController.RegisterMapObject(this.gameObject, image);
}
// Update is called once per frame
void Update()
{
}
}
I don't know why is this giving me the error?
Upvotes: 0
Views: 499
Reputation: 3884
Your mistake is likely here:
public static void RegisterMapObject(GameObject o, Image i)
{
Image image = Instantiate(i);
mapObjects.Add(new MapObject() { owner = o, icon = i });
}
You are instantiating the image, but then you pass on the prefab to your MapObject
.
Try doing:
mapObjects.Add(new MapObject() { owner = o, icon = image });
Upvotes: 1