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.
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.
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);
}
}
}