I want to take a component’s values and settings from one gameobject (in this case a particleSystem) and assign them to another Gameobject’s component’s values and settings. But I’m getting errors from my code. Is there something I’m doing wrong?
using UnityEngine;
using System.Collections;
public class AddFromOtherGameobject: MonoBehaviour {
public GameObject gameobject1;
public GameObject gameobject2;
// Use this for initialization
void Start () {
gameobject1.AddComponent("particleSystem");
gameobject1.particleSystem = gameobject2.particleSystem;
}
}
}
If I’m understanding the question, you have 2 objects with the same script attached, and you want to match all the property values on both objects? What I did to test this out (C#), I made a simple scene with a camera and two cubes. On each Cube, I attach Example.cs.
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
public float float1;
public float float2;
}
Now both cubes will have the example script with two properties. float1, and float2. Next, I wrote MatchProperties.cs, which uses UnityEditorInternal.ComponentUtility to copy component values from “go1”, and paste the values into the Example component on “go2” after 3 seconds. I did a simple GUILayout Label to show the change happen. Here is MatchProperties.cs, which I attached to the Main Camera.
using UnityEngine;
using System.Collections;
using UnityEditorInternal;
public class MatchProperties : MonoBehaviour
{
public GameObject go1;
public GameObject go2;
string label;
IEnumerator Start()
{
go1.GetComponent<Example>().float1 = 10;
go1.GetComponent<Example>().float2 = 20;
go2.GetComponent<Example>().float1 = 0;
go2.GetComponent<Example>().float2 = 0;
yield return new WaitForSeconds(3);
ComponentUtility.CopyComponent(go1.GetComponent<Example>());
ComponentUtility.PasteComponentValues(go2.GetComponent<Example>());
}
void Update()
{
label = "go1 - float1 = " + go1.GetComponent<Example>().float1 + "
Yep you can’t do that. A behaviour is associated with only one game object. You would need to copy the settings from one to the other. Unity Serializer can do that with it’s SerializeForDeserializeInto and DeserializeInto methods.