I am having an issue trying to use a set of prefabs to set the parent of them to the canvas (they are text objects, so I want them to delete the previous text object and use the next text prefab). Whenever I press the next button, it gives me this error
Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption (GameObject: ‘Question5 (TMP)(Clone)’).
UnityEngine.Transform:SetParent(Transform)
QuizManager:NextQuestion() (at Assets/Scripts/QuizManager.cs:75)
UnityEngine.EventSystems.EventSystem:Update()
I have looked up multiple ways to solve this, but I have not been able to find one that works for me. This is not the only problem I have encountered, the code I have also does not delete the previous question, although that might be because of how I link the object in the code. Here is all the code in question.
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class QuizManager : MonoBehaviour
{
public List<GameObject> answers;
public List<GameObject> questions;
public GameObject canvas;
private int i = 1;
private GameObject instantiatedQuestion;
private List<GameObject> instantiatedAnswers;
public void Start()
{
int j = 0;
float x = 0f;
float y = 0f;
i = 1;
GameObject uiObj = Instantiate(questions[0], new Vector2(450, 330), Quaternion.identity);
uiObj.transform.parent = canvas.transform;
instantiatedQuestion = uiObj;
for(j = 0; j < answers.Capacity; j++)
{
Debug.Log($"j = {j}");
if (j == 0)
{
x = 262.5f;
y = 224f;
} else if (j == 1)
{
x = 692.5f;
y = 224f;
} else if (j == 2)
{
x = 262.5f;
y = 139f;
} else if (j == 3)
{
x = 692.5f;
y = 139f;
}
GameObject answerObj = Instantiate(answers[j], new Vector2(x, y), Quaternion.identity);
answerObj.transform.parent = canvas.transform;
}
}
/**
* NextQuestion will load up the next question by deleting the last question object and instantiating
* the next object into the UI element
**/
public void NextQuestion()
{
i++;
if(i < questions.Capacity)
{
Destroy(instantiatedQuestion);
GameObject uiObj = new GameObject("myClone");
uiObj = Instantiate(questions[i], new Vector2(450, 330), Quaternion.identity);
uiObj.transform.SetParent(canvas.transform);
instantiatedQuestion = uiObj;
}
}
public void GoBack(string back)
{
Debug.Log("Going Back");
SceneManager.LoadScene(back);
}
}
Any help that can be provided is greatly appreciated.