What I’m trying to do is create an afterimage trail of a sprite character. To achieve this, I thought I’d use prefabs that get instantiated with the current frames sprite and then fade out while staying in position.
So I added a script that creates the prefabs and passes some variables via a method. On the prefab itself, I have a Sprite Renderer and another script that contains a death timer and this method:
public void ChangeSprite(Sprite newSprite, Texture2D texture) // would it be better to pass texture by reference here, so the texture isn't in memory twice?
{
//spriteRenderer.sprite = newSprite; // <-- This was my first naive attempt
displaySprite = Sprite.Create(texture,new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f);
spriteRenderer.sprite = displaySprite;
}
As you can see, I first thought it would be enough to just pass the sprite itself. The prefabs do get instantiated, but the Sprite Renderers’ sprite fields are all empty. I looked around the manual and found the Sprite.Create method, which I think I basically used correctly in the above example. However, above code gets me a NullReferenceException: “Object reference not set to an instance of an object” that points to the line that says “displaySprite = …” in my script.
The main difference between my script and the example code from the manual is that in the manual, the Sprite.Create function is in the start method and the sprite it creates gets used later.
When I was reading about Sprite.Create, I found some threads of people who thought it was slow, so I tried setting up a one second timer inside the prefabs Update function, that would call another method to actually change the sprite to the one created in ChangeSprite (which I guess is a misnomer then) and that actually worked.
Now I could perhaps set the timer for the sprite change as low as .05 or so and see how that turns out, but it’s still bothering me. Even though I’m not planning on using this prefab excessively, only on some actions the main character performs, and then probably not on every frame either.
It might not be a huge impact, but maybe in the future I’ll want to dynamically assign more sprites and the load might add up? Isn’t there a better way to do this? I’m just trying to pass the exact sprite/graphic the main character is displaying at that point to a prefab…
Also, can someone answer the question in the code, about passing the texture2D by reference? Is that better/faster in this case, or is the difference negligible? As I understand it, passing it by value will create another texture2D in memory.