- Home /
Instantiate question
Hi, when instantiating an gameobject is there anyway I can have the values in the instantiated gameobject script be the same as another gameobject already in the scene? Here is my code:
public class PlayerController : MonoBehaviour {
public Interactable focus;
}
public class Arrow : MonoBehaviour
{
public PlayerController pc;
public Interactable currentTarget;
void Update()
{
currentTarget = pc.focus;
}
}
When I click on an gameobject in the game, the focus variable gets that object then the arrow prefab is instantiated but without having the currentTarget in the Arrow script, the same as the focus variable in the PlayerController script.
Sorry for the poor description of my problem.
Answer by FeedMyKids1 · Jun 18, 2020 at 12:17 AM
https://stackoverflow.com/questions/78536/deep-cloning-objects would show you about cloning objects in C#.
Because Monobehaviour doesn't allow constructors, you couldn't implement a copy constructor.
But since your values are public (and even if you make them private but give them public access through getters), you could put a method on the Arrow like
public void MakeThisCopyOf (Arrow arrowToCopy)
{
this.pc = arrowToCopy.pc;
this.currentTarget = arrowToCopy.currentTarget;
}
but that would be a huge pain in the ass depending on how many fields you're copying.
I'm wrong.
Look at $$anonymous$$agso's answer.
Pass your original gameobject into the Instantiate method of $$anonymous$$onobehaviour.Instantiate and it will give you an exact clone, with your fields set the same and everything.
Answer by Magso · Jun 18, 2020 at 09:33 AM
Instantiate returns an object type in other words anything the variable type is assigned to.
GameObject NewArrow;
NewArrow = Instantiate(...);
NewArrow.GetComponent<Script Name>().currentTarget = currentTarget;
GameObject newArrow = Instantiate (ORIGINAL_ARROW_REFERENCE) as GameObject
and you don't even need to set the fields up.
Your answer
Follow this Question
Related Questions
"Quaternion.LookRotation" not working when Instantiate 1 Answer
GameObject variable points to instance instead of prefab when prefab gets instantiated 2 Answers
How to instantiate once when boolean changes 1 Answer
Instantiate an instance? 1 Answer
Tutorial for manual instantiation of prefabs yields null exception 2 Answers