Can't add component 'Animation' totestObj because such a component is already added to the game object

I want to AddoCompornent "Animation" in the Update() function of the script to testObj.

I wrote and executed the following code, but I get an error.

using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
using System;

public class unityRecieve : MonoBehaviour
{
    // Start is called 
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        GameObject obj = GameObject.Find("testObj");
        obj.AddComponent<Animation>();
    }
}

The error details are as follows.

Can't add component 'Animation' totestObj because such a component is already added to the game object!

How can I skip the processing if the Animation Compornent has already been added to the Gameobject?

I need to rename "testObj" dynamically, so I want to handle it in the Update () function instead of in the Startup () function.

I want to AddComponent after checking if Animation component is already added to testObj using if statement as follows. However, an error occurs if the following method is used. I don't know the correct way.

using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
using System;

public class unityRecieve : MonoBehaviour
{
    public Animation animation;

    // Start is called 
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        GameObject obj = GameObject.Find("testObj");
        animation = GetComponent<Animation>(obj);
        if(animation == null)
        {
            obj.AddComponent<Animation>();
        }
    }
}

1 answer

  • answered 2019-11-14 06:21 derHugo

    I'ld say the exception message is self-explanatory enough.


    You can ofcourse simply use

    if(!obj.GetComponent<Animation>())
        obj.AddComponent<Animation>();
    

    However, as mentioned in the comments both Find and GetComponent are very expensive calls and should never be done in Update. In general you should avoid them as much as possible.


    An alternative might be e.g.

    void Update() { if(isInitialized) return;

        var obj = GameObject.Find("testObj");
        obj.AddComponent<Animation>();
        isInitialized = true;
    }
    

    But also this is quite inefficient. You should rather simply do it only once and only when the UDP command is received.


    I still don't see the reason why you can't

    • add the Animation to the GameObject via the Inspector Add Component by default before even starting the App
    • create a Prefab which already has the Animation attached (via the Inspector Add Component)
    • use Find only once in Start and store the reference to it in a field

    • in general already reference the obj in a field via the Inspector