r/Unity3D – Telegram
r/Unity3D
265 subscribers
12.7K photos
15.6K videos
14 files
48.1K links
News about the Unity engine and project showcases from Reddit. Made possible with @reddit2telegram (@r_channels).
Download Telegram
Efficient way to cycle through sprites in a texture?

I have have a texture with multiple sprites like this:

https://preview.redd.it/0kdpez14sazd1.png?width=245&format=png&auto=webp&s=198405b4bc607a8d66f68d633c86c028675a741b

What I want to do is basically at certain points switch between different sprites in the texture (in the case, it is a crop that is growing with different stages). What I have come up with so far is this:

using ProjectEdg.CoreModule;
using UnityEngine;

namespace ProjectEdg.TextureModule {
public class MultiTextureComponent : MonoBehaviour {
[SerializeField]
private SpriteRenderer _spriteRenderer;

[FoldoutGroup("Debug")]
[SerializeField]
[ReadOnly]
private Texture2D _texture;

[FoldoutGroup("Debug")]
[SerializeField]
[ReadOnly]
private MultiTextureData _multiTextureData;

private float _updateArea = 1f;

private int stage;

private string[] _spriteNames = new string[] { "ParsnipPlant1", "ParsnipPlant2", "ParsnipPlant3" };

#region lifecycle

private void Start() {
_multiTextureData = ResourceManager.Instance.GetTextureData("FarmingCrops");
_texture = ResourceManager.Instance.GetTexture("FarmingCrops");

SetCroppedArea(_spriteNames[stage % 3]);
}

private void Update() {
if (_updateArea > 0) {
_updateArea -= Time.deltaTime;

return;
}

stage += 1;
SetCroppedArea(_spriteNames[stage % 3]);
_updateArea = 1f;
}

#endregion

private void SetCroppedArea(string spriteName) {
var spriteData = ResourceManager.Instance.GetTextureSpriteData("FarmingCrops", spriteName);

if (spriteData == null) {
return;
}

var startingPosition = new Vector2Int(spriteData.StartX, spriteData.StartY);
var size = new Vector2Int(spriteData.Width, spriteData.Height);
var centerOffset = new Vector2(
spriteData.CenterOffsetX != -1 ? spriteData.CenterOffsetX : _multiTextureData.DefaultCenterOffsetX,
spriteData.CenterOffsetY != -1 ? spriteData.CenterOffsetY : _multiTextureData.DefaultCenterOffsetY
);

if (startingPosition.x + size.x > _texture.width || startingPosition.y + size.y > _texture.height) {
LogManager.LogError("the attempted crop area is out of bounds of the texture");

return;
}

var croppedPixels = _texture.GetPixels(startingPosition.x, startingPosition.y, size.x, size.y);
var croppedTexture = new Texture2D(size.x, size.y);

croppedTexture.SetPixels(croppedPixels);
croppedTexture.filterMode = FilterMode.Point;
croppedTexture.Apply();

_spriteRenderer.sprite = Sprite.Create(
croppedTexture,
new Rect(0, 0, size.x, size.y),
new Vector2(centerOffset.x / spriteData.Width, centerOffset.y / spriteData.Height),
_multiTextureData.PixelsPerUnit
);
}
}
}

While this works, my concern with this approach is that each time I am changing the sprite to render, I am creating a new `Texture2D` and `Sprite` and was wondering if there is a more efficient way to do this. For example in Godot, I can have a sprite use the main texture and then just set the region rect for the sprite without creating this extra data (at least explicitly, I don't know what is happening under the hood) and was wondering if there is something like that in Unity?

The best approach I can think of is when loading the main texture, I create and cache the individual textures / sprites in the texture and then just reference those cached items when I need to (like my current example is doing for the main texture). This has the downside that I have to store
all the textures / sprites in memory even when I am not using them.

Is this a good approach? Is there something else already built-in that would handle part of this for me?

https://redd.it/1gl0r3m
@r_Unity3D
Why won't pressing a button on my controller trigger the function?

I've started making a new game recently and I've been trying to add controller support as I implement more things. I've created a function that is supposed to show and hide the inventory by pressing either E on a keyboard or the "North Button" on a controller (Triangle on playstation, X on switch and Y on xbox). Pressing E works fine, but pressing Triangle on my PS5 controller does nothing. Unity isn't telling me there's an error, it still detects when I press the button elsewhere in Unity, and moving with the Left Stick still works perfectly fine.
Can anyone figure out what I'm doing wrong?

https://preview.redd.it/sicm2qudibzd1.png?width=1097&format=png&auto=webp&s=4bee7e4c7efe02d66bfc791c6ad62053b9c30d6e

https://preview.redd.it/s4an6rudibzd1.png?width=1105&format=png&auto=webp&s=6396253e45a4e8bd671764feae498e7c812be08b

openInventory.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class openInventory : MonoBehaviour
{
@PlayerGmaepadControler controls;

void Awake()
{
controls = new @PlayerGmaepadControler();

controls.Gameplay.ToggleInventory.performed += ctx => ToggleInventory();
}

[SerializeField] GameObject _object;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
ToggleInventory();
}
}

void ToggleInventory()
{
bool currentState = _object.activeSelf;
_object.SetActive(!currentState);
}
}

https://redd.it/1gl47cv
@r_Unity3D
Squatting Frog vs Standing Frog: What Logic for a Puzzle World?
https://redd.it/1gl4r3m
@r_Unity3D
We patched our game ARGO on our first anniversary on steam!
https://redd.it/1gl6r3d
@r_Unity3D
How to use hold Touch as Input to execute action in Update function? For mobile.

Hey guys, I was inspired by Dani Dev to start gamedev and I've spent quite a few months just creating my first game for mobile similar to his farty Rocket that he created in 1 hour lol. the problem is I can't find any way to move my player when the user taps and holds the screen. I've done everything else perfectly fine but I just don't understand any tutorial on this type of mobile input for this silly little 2d game. this is my code:

void Update()

{

if (gameManager.IsState(GameState.Playing))

{

//Need to put Mobile inputs here but whichever one i try it with it doesn't accomplish anything.***

if (Input.GetKey(KeyCode.Space) || Input.GetKey(KeyCode.UpArrow))

rb2d.AddForce(Vector2.up * flyForce * Time.deltaTime * 1000f);



// Rotates ship

float angle = Mathf.Atan(rb2d.velocity.y / rotation) * Mathf.Rad2Deg;

transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));

}

} this is the video that can explain what kind of input I am talking about.. at 4:41 https://youtu.be/LrFm8hq3gsA?si=BWcEf8hJJkPkdjQh

https://redd.it/1gl8us3
@r_Unity3D
Media is too big
VIEW IN TELEGRAM
We just launched our first game Tiny House Simulator where you build tiny homes for clients and explore the open world


https://redd.it/1gl7en0
@r_Unity3D
I have a hexagon tile map grid. I want to implement a feature where honey combs can be dragged and placed at predetermined positions. Is that possible with the tile map or do I have to make my own grid system?
https://redd.it/1gliqb7
@r_Unity3D
My first Steam game has received quite a few visits over the past two days, but it’s only sold a few copies. Is there anything I can improve, or is this normal?
https://redd.it/1glkfil
@r_Unity3D
This media is not supported in your browser
VIEW IN TELEGRAM
It's been a crazy week for the world. Maybe lighting one up with your cat by the window is what you need to recover.

https://redd.it/1glkz2x
@r_Unity3D
This media is not supported in your browser
VIEW IN TELEGRAM
I made my own 3D ECS sandbox game with ~1 million voxels (250 fps).

https://redd.it/1glksgf
@r_Unity3D
Upload to Playstore fails due to API 28, game created in Editor 2019.3.0f5, needs min 34

Hi,

I have a game I developed in 2019-2020 and I was just learning Unity. I forgot all about it and now I want to release it. Game works, I build apk and it works on my phone and others, but when I try to release it on Google Play store I get error Your app targets API level 28 and needs at least 34.

This is how I started: installed Unity hub, installed Editor 2019.3.0f5 in which game was build (is this wrong?).

After I do that in folder D:\\Editor\\2019.3.0f5\\Editor\\Data\\PlaybackEngines\\AndroidPlayer\\SDK\\build-tools I have only folder 28.0.3

I tried installing Android studio, downloading 35 and pasting it in this folder. Should I delete 28 before running Unity again?

Is it proper way to get higher SDK/API to just get it from Android Studio and copy paste the entire unzipped folder to this Unity folder?

Sorry if this is low hanging fruit kind of question but just want to solve it so I can progress with my other projects.

Any help is appreciated.

https://redd.it/1gloglx
@r_Unity3D
In our action roguelite game, Anomaly President, you fight crime at night and try to win the presidential election in the mornings, and it’s featured in the Lands of the Crescent event! If the game’s theme caught your interest, we’d be thrilled if you could add it to your wishlist :)))
https://redd.it/1glq769
@r_Unity3D
My Tycoon/Strategy game, Firearms Factory, where your candy factory is turned into an arms workshop by government force, is part of the Lands of the Crescent event. While the game’s demo is not available yet, I’d be happy if you could add it to your wishlist if the theme interests you.
https://redd.it/1glquew
@r_Unity3D
I made an asset/tool that helps you making your netcode for gameobjects game, it focuses on providing an alternative to rpcs. While not trying to replace them completly. Would anyone want to leave feedback in the comments?

https://redd.it/1glt4q2
@r_Unity3D