#๐ผ๏ธโ2d-tools
1 messages ยท Page 37 of 1
where would the bullet spawn then
at the guns location, plus an offset to appear at end of muzzle
they mean to say, why can't the fire point move with the gun
so make the firepoint a child of the gun or??
try it ๐
just have the script run on gun, delete firepoint
but then some of the code has to change no?
I would recommend you to first of all setup VS or VSCode whatever that is to provide autocomplete. Links on how to do that are pinned in #๐ปโcode-beginner
what will vs do
i would recommend you write instantiate(bulletPrefab, transform.position, transform.rotation); when having weapon script added to gun object
ill try it now
vs is short for visual studio, the ide youre using to edit code rn
it shoots near the legs and it still goes to the right
???
wheres the center of the gun gameobject
click it in the heirarchy window
press w to select move tool if not already so
where the y and x vectors meet should be center of gameobject
public Sprite[] imageList = new Sprite[] {
Sprite red = Resources.Load ("Assets/Assets/GFX/RED"),
Sprite blue = Resources.Load ("Assets/Assets/GFX/BLUE"),
Sprite green = Resources.Load ("Assets/Assets/GFX/GREEN");
};
is dis right
dumb it down please
?
is that the center of the gun?
yes thats the gun chosen
if it runs, i guess
ok
in that photo the gun itself was selected
ok
why the cubes
it wouldve been much easier but i made the gun when i was like 2 days into it
yes i know
but its already made
doyou want me to delete it?
for best practices, yes
ok hold on
it doesnt take long
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetScript : MonoBehaviour
{
int Color = 0;
public Sprite[] image;
public void onClick() {
Color = Random.Range(0, 2);
Debug.Log(Color);
}
}```
@rain ingot
look in the inspector window, you should be able to set size of array and assign the sprites there
for onclick i need to add a button?
yes
hello
ok
it doesnt log
did you drag the gameobject with the script into onclick event
did you set the function to onClick from TargetScript class
ok
is the button a child of a canvas
no
it shoud be
its a sprite now
create a canvas ui object, put button as child under the canvas
do i place the script
yes
ok ill try it
place it onto the gun
it still shoots to the right
and now it doesnt even shoot from the gun
shoots from here
offset the position
when you call instantiate, add new Vector3(x,y,z) to transform.position
mhm def understood that
instantiate(bulletPrefab, transform.position + new Vector3(0,0,0), transform.rotation);
adjust x,y,z values of new Vector3
to what numbers
find out through trial and error
whats supposed to be happening with this piece of code exactly?
so i can understand what im even tyring to do
u mean moves this?
no
the center stays the same
when you spawn the bullet, it references that center
the code adds to the position of the center
hence offset
aha
if you want to change the center to be at the end of the gun, you have to change the pivot position in sprite editor
thats fine
nvm you shouldnt add offset to position, thats bad practice
do this
click on the sprite in the project window, look to inspector
should see this
do i return the code to what it used to be
no
ok
do i press sprite editor
yes
ok now what
change pivot from center to customized
ight
trial and error until pivot is at the end of the gun
its moves the pivot
it does not move the sprite
or the gun
ohh this thing
yes
ok ok
move blue circle to end of gun
I have a character in a multiplayer game. I want to be able to change the color of the character but certain parts should always be the same color. So what's the best way to change the color on some parts without having to make lots of different sprites and animations?
whatever u want
yes
but it still looks the same in scene?
i did the canvas thing still doesnt work
yes
ah ok
alright
it works
but the direction is still fucked
shoots right both ways
is there an active eventsystem in the scene
just like always
yes
cant u just change the color component?
me and the enemy bot are facing this problem by the way the bot still has a firepoint
change the velocity of bullet to negative when left button is clicked
but i shoot with left button on both sides dont i?
does the button block raycasts
That changes the color of the entire sprite. Some parts of the sprite are not supposed to change color though
wdym
ur pfp really macthes whats going on right now huh
matches*
i see, i would just separate sprite into pieces which should have the color change then
run the game, click eventsystem in hierarchy window, hover mouse over button, look in inspector window for raycastable target
i mean the input for moving character left
not left mouse button
what
im trying to make the center face left when i turn left
is that what the velocity does
velocity of bullet makes would make it move in the positive or negative direction
nope cant see raycastable object
ohh
how do i do that
and if statment?
an*
i tried to do this but i have no idea how i can write it
if left input, multiply bullet velocity by -1, if right input, reset bullet velocity to original value
is the button enabled
how would i identify left and right
-1 is left
yes
left = -1**
you should be looking for this info
but i aswell am not sure
right should just be the original value of bullet velocity, left should be negative value of bullet velocity
yes
so now i need to tell it that whne i press a it changes it to negative and when i press d it changes back to positive?
you ran the game, and hovered mouse over button?
yes
and this is the eventsystem info?
yes
yes
?
nvm that works
afk
current raycast isnt the button when you hover over it?
nope
if youre writing that code in bullet script, no
target is the button
did you configure canvas component
change render mode to world space
drag main camera into render camera
change render mode to screen space, then back to world space
to automatically fit canvas to screen then be able to move buttons to gameobject position in world space
where is the button in the scene
child of canvas
not hierarchy, the scene view
in midle of my camera
why are the button and button sprite separate gameobjects?
delete sprite gameobject, add image component to button
now the button hitbox is too big
change the width and height of the rect transform
it changes the image troo
the width and height of rect trransform should be the same ratio as the image dimensions
im not
is that wrong
im writing it in the weapon script
if youre writing it player controller (which u should), then you'll need to reference the bullet script to access the bullet speed variable
Yes
increase the upper bound
its bad practice
ok i have two scripts for the movement sinc ei followed brackeys tutroial
now i need to do the sprite swiching
you already have input code in player controller
this one was brought into the tutorial after putting the character controller
when i only put the character controller and attempted to move
it only changed my direction
so i think i have to put the cod einto character controller
?
nvm, just keep it in weapon script
get the script component from the referenced gameobject
can u type it
now how do i load the images form array to the image component
like this but instead of rb2d its bullet?
assign the sprite renderer component
and then speed
bullet = GetComponent<speed>();
?
and
public Bullet bullet;
?
declare public GameObject bullet;
?
you reference the script from the prefab
i use the image component?
the script that has the bullet speed variable isnt called Weapon?
the script im trying to call isnt called weapon yes
the script im currently typing in is weapon
which script has bullet speed variable
the bullet script
the image component is for the button, youre trying to use the sprite array for the character?
?
reference the bullet speed variable by assigning bullet gameobjectbullet.GetComponent<Bullet>();
from weapon script
i recommend you rename bullet gameobject to bulletScript in weapon script
in void update correct?
assign it in start()
write if statements in update()
if (input.getbuttondown("a"))
yes i know
speed = -10
else (input.getbuttondown("d"))
reference bullet speed by bulletScript.speed
does that work
idk
run it
Assets\TargetScript.cs(11,17): error CS0103: The name 'Target' does not exist in the current context
Assets\TargetScript.cs(11,37): error CS0246: The type or namespace name 'Image' could not be found (are you missing a using directive or an assembly reference?)
should probably delete "left" and "right"
or i can be epic and replace 10 and -10 with left and right
nah too much work
alright i deleted them
replace 10 with bulletSpeed, replace -10 with -bulletSpeed
ok
.
theres no such thing as bulletspeed in the script tho?
what are you trying to do?
or is simply saying bullet going to refrence the script
image = Target.GetComponent<Image>();
Assets\TargetScript.cs(11,41): error CS0246: The type or namespace name 'Image' could not be found (are you missing a using directive or an assembly reference?)
rename left to bulletSpeed
theres no speed in weapon but there is speed in bullet
delete right
thats the error
what are you trying to do?
just initialize bulletSpeed to 10
switch sprite from a array
assign the spriterenderer of the character to sprite array index
do i save and hit play now
on a button
?
assign the button image to sprite array index
how
you dont have to ask
ok sorry
what
why does it expect a ; in else???
40 is the end of the code
show full code
GetComponent<Image>().sprite = sprite[index];
change the else to an if
else if
no
or just a different if
just if() and if()
is speed a public variable
Assets\TargetScript.cs(14,22): error CS0246: The type or namespace name 'Image' could not be found (are you missing a using directive or an assembly reference?)
Assets\TargetScript.cs(14,40): error CS0119: 'Sprite' is a type, which is not valid in the given context
is this script in the button
yes
show code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetScript : MonoBehaviour
{
int Color = 0;
public Sprite[] image;
public void onClick() {
Color = Random.Range(0, 3);
Debug.Log(Color);
GetComponent<Image>().sprite = Sprite[Color];
}
}
should be GetComponent<Image>().sprite = image[Color];
not GetComponent<Image>().sprite = Sprite[Color];
but my arrays name is Sprite
your array name is image
oof
you declare image as a Sprite array
Assets\TargetScript.cs(14,22): error CS0246: The type or namespace name 'Image' could not be found (are you missing a using directive or an assembly reference?)
show code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetScript : MonoBehaviour
{
int Color = 0;
public Sprite[] image;
public void onClick() {
Color = Random.Range(0, 3);
Debug.Log(Color);
GetComponent<Image>().sprite = image[Color];
}
}
add using UnityEngine.UI; namespace
sorry i had to afk
and i styill gotta afk
so wait a bit
@rare parrot
hello?
?
make it public
the error still appears tho
i made it public and saved
its still here
even in th ebullet script itsd public
i think its talking about bulletScript
idk
bulletScript gets assigned the reference to Bullet script from bullet gameobejct
is the class public
yes'
how do i make my code recognize the last facing direction & use the corresponding run animation for up & down movement?
show animator window
show code in bullet script
i setup a blend tree
i dont have any up/down animations so i want to use the left running animation when going down, IF last facing direction was left
and the same thing for the right
did you assign the bulletScript reference in the inspector window
nvm
not familiar with blend trees, why use a blend tree as opposed to a finite state machine?
i would have the same error with a state machine
i just need some way in the code to recognize the last direction
and default to the right animation
it recognizes current direction by use horizontal and vertical input right
yeah
can u store current input in a variable for previous input to recognize last direction
i guess
bullet script on the bullet
that on the gun?
write bulletScript = bulletPrefab.GetComponent<Bullet>();
in weapon script
in start()
the error says the problem is within here
ok
a new one
show code
declare public Bullet bulletScript, not public GameObject bulletScript
back
lets goo theyre gone
@rare parrot
the only error left is just a triangle error
ive been ignoring it since like day 3
yo it wont let me choose anything'
@rare parrot
i can put the bullet prefab in there
just not the script
does the bullet prefab work
hes
yes
input button a isnt an input
lol
should i put horizontal instead or??
in the player movement a and d are both calle dhorizontal though
hm
ill just make ne inputs lol
new'
IT WORKSSS
@rare parrot THANK YOU SO MUCH FOR PUTTING THRU MY BULLSHIT
np
o shit wait how do i do this to my enemy tho
bots dont press a or d
fuckkkkkkkkkk
where code is for move bot left or move bot right, same applies
what
bot doesnt go left or right it follows me
three enemy scripts
well two
enemy gfx isnt being used
theres like no code that tells it to face left or right@rare parrot
thats the enemyAi
this is what makes it shoot
it shoots non stop even if im not in view
if the bot is following you from left, set that enemy's bullet velocity to positive, if the bot is following you from the right, set that enemy's bullet velocity to negative
??
the enemy is suspended in air?
its a flying enemy
and you want the enemy to face towards the player?
supposed to be like a robot turret thing
yes
currently it isnt
but when i press play it does
not really right at me but like left or right
Consider separating input from the behaviour. It can allow you to use the same scripts regardless whether they are a player or an enemy.
what
uh dumb it down?
behaviour as in which way theyre going?
liek detect if theyre going - or +?
Move the input collection to a separate script
PlayerInput listens for input devices and AIInput generates them based on AI decisions
what
Yea fire could just be a fire bool
to make turrent face towards player, run transform.LookAt(player); in update() of turret
in enemy ai script correct?
and unfreeze rotation?
yes
hm might fuck up things
since when i unfreeze it
the moment i touch it it breaks the bot
how?
idk i can show u in screen sahre tho
oh wait
it doesnt do it anymore
it used to go crazy all around the map
and some of the time it get touched and just goes flying
i mean it still does go flying but not as bad
since after i make it go flying it stops moving
but now it doesnt
ill try the code
it already has atarget for player
do i just put target
sure
sure
change to 3d collider
nvm
doesnt it work just by adding a 2d rigidbody?
rotation for x and y doesnt exist in 2d
it decided to go to the core of the earth
it also still looked at me without its sprite
the suggested LookAt() but it requires Vector3 to be passed
with rigidbody 3d too?
just google how to rotate object towards player 2d unity
instantiate enemy projectile at transform.position and transform.rotation
offset position if u want by changing pivot of enemy sprite
enemy projectile is also the same bullet
thats fine
nvm
your bullet script has player code in it
just create a new prefab, assign it the same sprite
perfect
ok
do i copy everything from the original bullet
just the code that moves it
?
but that causes the entity to die tho
theres nothing for the player??
thats the entire script for the bullet btw
nothing else nothing less
i mean create a new bullet prefab for the enemy
create new script, should only contain code to move it
so basically remove what i crossed out right?
that code is for damaging the player?
uh
damagin any entity
the enemy bullet should not damage itself
it doesnt
it doesnt have the entityhealth script
only entites with that script get damaged then deleted
?
?
sorry
got distracted
the crossed out has the entityhealth called in it
this is the entityhealth
here its called
so what is the issue
ok so dont
itll immediatley one shot everything
and since i crossed out destory aswell
it wont even one shot them
it doesnt do anything
so i literally cant delete anything from bullet lol
nothing involves the player
neither here
btoh can be applied to absolutley anything
so what is the issue again
u told me to make a new bullet and delete stuff of it
i cant delete anything or i break the bullet
you said it was deleting the turret right?
nvm i misunderstood
instantiate the bullet prefab from turret\
in what script
in whichever script u want to control enemy fire
in enemyshoot?
sure
its the script that allows it to shoot
replace it with transform instead of firepoint yes?
ok done
the firerate is second or?
i dont really understand it
i yoinked the script lol
yes
ok wait i gotta brb
Vector2 newPos;
newPos.x = Random.Range(1920, 0);
newPos.y = Random.Range(1080, 0);
Target.transform.position = newPos;
Assets\TargetScript.cs(23,9): error CS0103: The name 'Target' does not exist in the current context
why does it not work
You don't have a variable named Target defined
how do i do like on click my target moves rando,ly on the screen
That code would work but you need to actually have a variable called Target
how
how do i declare a variable thats a gameobject
?
Looks like you only care about the Transform so why not just use Transform
But if you want a different type, just use that type instead of Transform
GameObject variablename
Assets\TargetScript.cs(23,16): error CS1061: 'GameObject' does not contain a definition for 'Transform' and no accessible extension method 'Transform' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
Instead of this
Vector2 newPos;
newPos.x = Random.Range(0, 1920);
newPos.y = Random.Range(0, 1080);
Transform.Target = newPos;
1
UnityEngine.Debug:Log (object)
TargetScript:onClick () (at Assets/TargetScript.cs:18)
UnityEngine.EventSystems.EventSystem:Update () (at C:/Program Files/Unity/Hub/Editor/2019.4.21f1/Editor/Data/Resources/PackageManager/BuiltInPackages/com.unity.ugui/Runtime/EventSystem/EventSystem.cs:377)
@rare parrot hello im back
soemone pls halp
Is there any way to make it instead of on keypress into a on button press. I have a button in my game already and it works fine but how do I make this line of code into a script that will let me access it through my ingame button?
It works with load menu but no idea how to make it pause the game
resume doesn't work, I tried
unless i coud make a new void thing
nvm
made void pause into public void pause and i got function pause working
all works
Why when I ask people, I always find out whats the problem
weird
It's magic
ikr
Also you need to think about the problem in a certain way to formulate a question properly
Gets the juices flowing
You want Target.transform.position = newPos;
@snow willow
someone pls help
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You need to assign the target in the inspector
someone pls halp
how do i make dis a float
newPos.x = Random.Range(0, 0.5);
newPos.y = Random.Range(0, 0.5);
newPos.x = Random.Range(0, 0.5f);
Vector2 newPos;
newPos.x = Random.Range(0, 0.1f);
newPos.y = Random.Range(0, 0.1f);
Target.transform.position = newPos;
returns
same position allways
help
my enemy is spawning bullets inside of itself
so it keeps killling itself
and now my player does it too
it was all going fine till i started it up
You can try calling Physics2D.IgnoreCollision between the player and the bullet when you spawn it
wont that ignore the enemy aswell?
this never happend nor did it happen befor ei closed unity
No it makes two specific Colliders ignore each other
alright how does it work
Physics2D.IgnoreCollision(collider1, collider2)?
Yes
When you spawn the bullet
?
this script spawns the bullet???
the bullet script is what spawns it??
oh wait nvm
That's the example code you showed right
Yeah
fire1
That makes sense
do i need to change anything
Physics2D.IgnoreCollision(bullet.GetComponent<Collider2D>(), GetComponent<Collider2D>());
player.circlecollidr2d?
You need to give it your player's Collider and the bullets Collider
bullet.capsulecollider2d?
You can just use Collider2D you don't need to say the specific type
Physics2D.IgnoreCollision(bullet.GetComponent<Bullet.CpasuleCollider2D>(), GetComponent<Player.CapsuleCollider2D>());
But you do need to use GetComponent
You'll need to call it for both of them then
Call ignore collision twice
oh
what about the 2nd option
also bullet?
yeah that makes sense
ok but uh
the enemy still fucked
it shoots inside of itself
when the pivot is infront of it
it doesnt shoot there
i have a script telling it spawn bullet there
but wait
if i do it for the enemy too
i wont be able to shoot it
IgnoreCollision only works for the specific two Colliders you give it
You only want to call it for a bullet and the entity that fired the bullet
They will still collide with everything else
so it doesnt work on the entire script
my robot enemy does this jiggly thing everytime he shoot sis that normal
only when he faces right
@snow willow
Hi, I'm a beginner in uniti, I have a problem, my character, when he collides with a wall, everything is trying to enter it exactly how to fix it in a 2D world
When colliding with an object, the character stops but still tries to enter the ngo but is pushed out
Why are you ignoring collisions for both player and enemy there
where then
picture or vid?
Should just be one or the other depending on who is shooting it
enemyshoot and weapon
one is for the the bot and one for th player
do i put each in those
@snow willow
uh what exaclty is happening in the picture?
is it not supposed to be standing inside of it?
so let me make a gif)
I don't know how to make the object harder
so that you cannot pass with proper acceleration
do you want the player inside it or outside the object
outside
okay are there any solutions?
yes I also have
tf
???
tf = the fuck
tf
yeah send a video please
And so here's the video
okay how left to right?
basically a 2d character only moves left to right if it wants to move up it jumps
if u dont know how watch brackeys 2d movement tutorial
he also has a top down tutroial
if u want
Okay, I'll go and take a look
does anyone know that if 2D extras comes with unity or u have to install it?
I think if you create a project with the 2D template it's included automatically
If not, everything is available in the package manager
i checked not there
i may have missed it
using unity 2019
maybe its on 202
anyways i installed it manually
its on preview only not verified
Yeah some packages are preview packages
What would be the best way to go about making a chess board? My knowledge of unity is very limited, so I'm not even sure if this is a project that I should work on quite yet.
Honestly probably not the best project to start with
It's not super beginner friendly
yeah, thought so
Maybe start with tic tac toe
Then checkers
Then chess lol
Maybe throw connect 4 in there haha
I already did tic tac toe
Ah ok good
So I am having a weird issue on this asteroids clone I am making, really it's just to learn a bit about how to approach 2D games with Unity...
The problem is that the script that checks whether the players bullet collided with the gameobject or not is destroyed I cannot simply store the amount of asteroids on that gameobject, I must pass it to another script that holds all of the games information for score, lives and the remaining objects in the scene. This script is attached to the scenes camera.
Lots of stuff spawns when I am instantiating more than 1 or 2 new objects.
Asteroid code
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("playerBullet"))
{
if (this.gameObject.CompareTag("largeAsteroid"))
{
SpawnAsteroids(mediumAsteroid, 2);
GameManager.playerScore += 30; //add 30 to player score
}
else if (this.gameObject.CompareTag("mediumAsteroid"))
{
SpawnAsteroids(smallAsteroid, 2);
GameManager.playerScore += 15; //add 15 to player score
}
else if (this.gameObject.CompareTag("smallAsteroid"))
{
gm.UpdateNumberOfAsteroids(-1);
GameManager.playerScore += 5; //add 5 to player score
}
Destroy(other.gameObject); //destroy the bullet
Destroy(this.gameObject); //destroy the asteroid
gm.playAsteroidSound();
}
}
void SpawnAsteroids(GameObject asteroidType, int spawnAmount)
{
if (spawnAmount != 0)
{
gm.UpdateNumberOfAsteroids(spawnAmount - 1);
for (int i = 0; i < spawnAmount; i++)
{
Instantiate(asteroidType, transform.position, transform.rotation);
}
}
}
I have a feeling that this could be due to instantiating many prefab objects at the same time, but I don't know how else to do this.
how do i spawn gameobjects and then remove them
I'm trying to implement the ability to climb on the ladder.
The problem I have is when the player gets to the platform he get stuck.
I tried to ignore collision with the ladder and platform layers and it worked fine, but when I'm on top of the ladder (on the platform) I can't go back down the ladder.
Any idea how can I solve this issue?
to respawn cant you just do scenemanage.loadscene("your scene"); to every enemy or thing you want to touch and die to respawn? and before you use scenemanage you have to import Unity.SceneManager
sorry i just started unity this weekend but if i were to guess if you were to collide with the ladder and press whatever you want to press (KeyDown.S) you can make the sprite's y value go down or you could just put it there until it reaches to the ground
Okay deleted last messages due to some confusion, I understand now... You could just extend the collider beyond the platform, and then only let the player down when he presses S or something
You could ignore collisions only when the player is going down the ladder... Or transform their position through the platform allowing them to jump down too
Also respawn wise you could reload the scene, but another option is just to instantiate a player prefab to a set location, and reset necessary variables such as health.
Okay last time I'll say stuff, and this is literally just because I had this problem...
If you are spawning objects and removing them, instantiating will work. But if it's spawning the same object many times then look into object pooling, it'll save a headache in the long term :)
{
if(collision.transform.tag == "Enemy")
{
collision.transform.GetComponent<AIShipController>().Damage(LaserDamage);
}
}```
Im having issues with this, it doesnt collide with the object, both objects have ridgidbodies and colliders
Thanks, but that doesn't fix my issue
So are you trying to push the enemy back or just damage them?
I'm tryna damage them
{
Health =- Damage;
Debug.Log("Hit" + Health);
}```
heres the damage script on the enemyt
If I understand correctly, you have your script to check collisions on the enemy, then you update that damage to another script? Sorry I just want to understand the aims of it a bit more
I will try make something in a few minutes though, on phone currently
I have a transform that when it collides with the enemie grabs the enemy script and tells it how much damage to apply
but they aint colliding
hi. i dont know how to check if the player touch the ground. do someone know?
sure so do you want to just hit the ground or do you want to make something happen once your player touches the ground
just to make sure if he is on the ground or not
you would need a box colllider 2d on the platform(ground)
you could just use debug log
and check the console
Unsure if this will work, too lazy to build a scene tbh.... This will at least confirm if they are colliding as I have no clue if the way you were applying damage works or not, I have never tried it that way. An alternative is to use "OnTriggerEnter2D" and set the colliders type to a trigger, it's a little checkbox in the inspector.
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Enemy")
{
Debug.Log("Enemy has been shot")
private int LaserDamage = 1;
Debug.Log("Laser Damage: " LaserDamage)
Damage(LaserDamage)
}
}
public void Damage(int Damage)
{
Health =- Damage;
Debug.Log("Hit" + Health);
}
Thats baso what i just done?
With debug logs to show you if they are colliding in inspector, and as I said, unsure if the way you were calling your Damage function and grabbing player health works or not. Also you could use trigger areas
Just to make sure, you have set the Enemy tag on your Enemy game object?
does anyone know how to move a sprite that has been created with: public Sprite Album;?
Yeah, idk why, but i just hit play without changin anything and it's working now so oof
thanks for the help
Album.transform.position = ???
can someone help make my instance as a child
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnerScript : MonoBehaviour {
public GameObject NPC;
public GameObject Canvas;
public int howMany;
void Start() {
spawn();
}
public void spawn() {
int Timer = 0;
for(Timer = 0; Timer < howMany; Timer++) {
Instantiate(NPC);
}
}
public void remove() {
GameObject.Destroy(NPC.gameObject);
}
}
how can I make my sprite a child of my game object?
If you pass the parent transform into Instantiate, it will become the parent of the new object
uhhhhh
Album.transform.parent = whatever
Sure, if you want the NPC to be a child of the canvas
ok
YOu can't
you can only set another transform as the parent
but I don't know how to set the transform of a sprite
I thought I needed a gameobject
Sounds like AlbumImg is a Sprite, which is just a file asset in your project
so it doesn't make sense
Share your code maybe?
public GameObject Album;
public Sprite AlbumImg;
Album.transform.parent = AlbumImg;
my goal is to transform.position = new Vector2(2,5);
That's like trying to set the parent of the album to an image file on your computer
Sprite is not an actual part of a GameObject in the world, it's just an image file
Then just do Album.transform.position = new Vector2(2, 5); ?
but then there is no img
I don't understand
Are you trying to figure out how to display your image in the game?
I'm trying to create sprites with code so I don't have to move everything into the hierarchy
and I want to parent with code so I don't have to manage it with the unity ui
Generally you use prefabs for that
and you can assign a sprite image to either a SpriteRenderer or a UI Image component
either of which can be parented in code
but you cannot parent a Sprite directly, since it's just an image file
ok thanks
so once i collide with the box collider with this code
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class tptolvl2 : MonoBehaviour
{
void tp(){
SceneManager.LoadScene("lvl2");
}
}```
it wont let me go to the scene
i also have this so i dont know what is wrong
Are you calling that function anywhere?
no
