How to avoid using same script on prefabs?

I have a script that makes an object out of every pixel in an image. I’m using a 64x64 image and I get about 3000 objects (transparent pixels are ignored), and each has a script that tracks collision with the character. Contact with the character, the script destroys the object.

using UnityEngine;

public class BubbleDestroy : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
       
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            Destroy(gameObject);
        }
    }

Is it normal to have so many identical scripts in a project, maybe there are better ways?
Give me a hint what can be done about this.

You can have as many or as few instances of any script you like.

If you’re having a performance issue, start with the profiler (Window → Analysis → Profiler).

If it’s something else you are trying to ask here…

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
  • links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?

I would rethink anything that wanted a whole collider per pixel. Consider your own pixel-collision scheme using a boxmarching technique (or even Bresenham’s Algorithm). Pixels in a bitmap are a good example of the “flyweight object” pattern. They’re just entries in an array, with no extra overhead of classes, references, fields, etc.

2 Likes

The simplest change is to use a string to specify the tag on a per-object basis. With this change you now only need a single instance of this script for every tag you want to compare against and perform this action on.

public class DestroyOnCollision : MonoBehaviour
{
    public string tag;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag(tag))
            Destroy(gameObject);
    }
}

Thanks for answers. I tried several different methods. now using a simple script attached to character

using UnityEngine;

public class Spike : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Bubble"))
        {
            Destroy(collision.gameObject);
        }
    }
}