L
L
Lexx Xell2019-06-20 12:31:56
Unity
Lexx Xell, 2019-06-20 12:31:56

Unity: How to display multiple sprites in one object?

How to display multiple sprites for one object?
Let me explain with an example what I want to achieve.
An object, say, a car wheel. It, according to the conditions, should be drawn separately, like a sandwich from sprites:

  1. Tire
  2. Disk
  3. Cap

There are several different wheel rim sprites and the hubcap may or may not be fitted.
I tried to organize it like this: I
created a GameObject (named it Wheel), added a Sprite Renderer to it, to which I tied a tire sprite, because. he won't change. In Wheel, I created four child GameObjects (Disk1, Disk2, Disk3, Cup), each Sprite Renderer with its own sprite.
In order not to go into the wilds of the conditions for changing one or another disc on the wheel, I will simplify the task.
Added a collider and a mouse click processing script to the Wheel:
using UnityEngine;

public class Wheel : MonoBehaviour {

  void OnMouseDown(){
                ???????????
  }
}

Instead of question marks, there should be a code that turns the wheel cap display on and off. I understand that you need to manipulate
.GetComponent<SpriteRenderer> ().enabled = true/false

but I don't know how to access the SpriteRenderer of the child object.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2019-06-20
@LexxXell

but I don't know how to access the SpriteRenderer of the child object.

The most correct - through [SerializeField] - and drag in the inspector.
Wrong, but working - through all sorts of FindObject using names / tags / layers / label scripts.

D
Denis Gaydak, 2019-06-20
@MrMureno

If the caps and wheels differ only in texture. then I would suggest doing a more optimal thing

using UnityEngine;

public class Wheel : MonoBehaviour {

public Texture[] textures;
public Sprite targetSprite;

  void OnMouseDown(){
        targetSprite.sprite = textures[0]; // или любой другой номер или логика выбора.
  }
}

the code is approximate) did not check in Unity)) maybe it was sealed up somewhere. but the principle itself is important to catch.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question