using UnityEngine;
using System.Collections;
using System;
public class CopyComponents : MonoBehaviour {
Component[]components;
public GameObject SourceGameObject;
public GameObject TargetGameObjec;
static Type CompType;
void Start () {
if(SourceGameObject==null)SourceGameObject=gameObject;
components=SourceGameObject.GetComponents<Component>();
for (int i = 0; i < components.Length; ++i) {
if(components_!=null&&components*!=this){*_
_ if(components*==null) Debug.LogWarning(“Warning, component n°”+i+“not found in this project”); }*_
* }*
* void Update () {*
* }* }
This is my script. Basically, as the title, I want copy all components (or Behaviour) and paste to another GameObject. But with my code return this error: Assets/CopyComponents.cs(20,62): error CS0118: CopyComponents.CompType' is a field’ but a `type’ was expected Anyone can help me?
UnityEditorInternal.ComponentUtility.PasteComponentAsNew(targetGameObject); But that’s obviously not at runtime, so not sure if that answers the question in this case, but very useful as a tool in the editor.
Instead of setting a type at compile time, pass a type’s name as a parameter in runtime. I’m not sure if you need to pass CompType.ToString() or CompType.Name, but probably both work.
ok I solve the copy of components… But are not a real copy. I want the same state, with all same variables for all components… And reflection not work, my field array is always empty!
Yep, you have to copy members, not only add component. See here.
Welcome to take a look at my Component Clipboard, a convenient utility to copy multiple components. But it currently can’t copy whole GameObject at once.
This question might duplicate with another. And there were answers.
Here is a method that copies all the components from one gameobject to another. I didn’t include the Transform, MeshFilter or MeshRenderer in the copy but that should be easy to edit.
private void CopySpecialComponents(GameObject _sourceGO, GameObject _targetGO)
{
foreach (var component in _sourceGO.GetComponents<Component>())
{
var componentType = component.GetType();
if (componentType != typeof(Transform) &&
componentType != typeof(MeshFilter) &&
componentType != typeof(MeshRenderer)
)
{
Debug.Log("Found a component of type " + component.GetType());
UnityEditorInternal.ComponentUtility.CopyComponent(component);
UnityEditorInternal.ComponentUtility.PasteComponentAsNew(_targetGO);
Debug.Log( "Copied " + component.GetType() + " from " + _sourceGO.name + " to " + _targetGO.name);
}
}
}