- Home /
How to give an image to a sprite in c# code?
I am making a game with where the main character shoots a gun. I have made it so each time the player presses "E" it creates a new bullet, a collider as a trigger (to check if it hit a target), some code to tell it how to move and a sprite renderer but when I can't figure out how to give the sprite renderer a picture. I tried using file paths but, I have no clue what I am doing. My code looks like:
string bulletPath = "../Assets/Fighting/Bullet.png";
if (Input.GetKeyDown("e"))
{
GameObject Bullet = new GameObject("Bullet");
BoxCollider2D hit = Bullet.AddComponent<BoxCollider2D>();
Bullet.AddComponent<Bullet>();
Bullet.AddComponent<SpriteRenderer>();
Bullet bullet = Bullet.GetComponent<Bullet>() ;
SpriteRenderer renderer = Bullet.GetComponent<SpriteRenderer>();
renderer.sprite = Resources.Load<Sprite>(bulletPath);
hit.isTrigger = true;
}
If you have any suggestions they would be greatly appreciated
Answer by tablazonsimon · Mar 10, 2019 at 04:25 AM
Instead of having to generate all of that every time you press "E", I think you should just make a "prefab". You create the bullet in the heirarchy, collider and picture and all. Then you drag that thing back to your assets to create a prefab. This "prefab" is what you make appear every time you press "e".
https://docs.unity3d.com/Manual/Prefabs.html
And then, you "instantiate" the prefab to make it appear. Read the "firing a rocket launcher" part.
Your answer
Follow this Question
Related Questions
How to stop a sliced image from shrinking with the container? 0 Answers
Best Image Formats, Sizes, and Resolutions for Unity Sprites? 2 Answers
How can i change the sprite image of button in run time of a 2d game 1 Answer
Cast object as sprite for UI Image 1 Answer
Can't get various different sprites to change on a UI *Image*. 0 Answers