#💻┃code-beginner

1 messages · Page 49 of 1

acoustic arch
#

that's why i'm confused

#

cause i did what it asked

summer stump
#

What course is it?

acoustic arch
#

have you heard of Sololearn?

#

it's just an app for learning computer stuff

summer stump
acoustic arch
#

alright

#

it's just picky

summer stump
#

It also has super weird picky specifications sometimes
Like one answer is right, but not the one they want

acoustic arch
#

i wish i could skip all this easy stuff cause i already do it a bunch

acoustic arch
summer stump
inland canopy
#

can someone help me with:
I want the player(ball) to rotate right when its moving towards right and
rotate left when its moving left

last grove
#

is it possible to combine a transform.up with a euler angle rotation?

teal viper
teal viper
last grove
#

I want to maintain a look direction while also changing the transforms rotation

wintry quarry
#

You can use Quaternion.LookRotation to create a rotation with a given look direction+ an "up" direction to determine the roll

last grove
#
            if (transform.eulerAngles.x == 180 || transform.eulerAngles.z == 180)
            {
                transform.rotation *= Quaternion.Euler(0, -prevLookDirection, 0);
            }
            else
            {
                transform.rotation *= Quaternion.Euler(0, prevLookDirection, 0);
            }```This is what I've got rn
wintry quarry
#

Yeah don't do that

last grove
#

ignore the if statement

wintry quarry
#

Euler angles are usually the worst way to do things

#

You want to look a certain way and align to a surface normal?

#

Use Vector3.ProjectOnPlane to project your look direction on the surface.

Then use that result with Quaternion.LookRotation and the surface normal again as the up param

last grove
#

That kind of worked

#

Only problems are now each time I change surfaces I get turned to look directly at the surface, also being completely upside down doesn’t work

wintry quarry
#

Is being upside down something you need to do?

#

You haven't really explained what you're trying to accomplish

queen adder
#

Hi, imagine this is a bit of a stupid question, but my UI button won't click. When i click it it selects the items behind it. I did set the right sorting order but still the same.

summer stump
#

Not sure what you mean by select other things. Is that ui stuff too, or a raycast or what?

queen adder
summer stump
#

Do you mean you just want to SELECT the button OBJECT?

#

Maybe I was misunderstanding

queen adder
#

So like I add a UI button and I want to move it aroud, but i can't, it won't let me select it, it selects other things in the hierarchy

astral basin
#

when using rb2d AddForce, does it matter if i put it in fixedupdate or regularupdate?

summer stump
queen adder
summer stump
queen adder
#

I put the ui buttons in here:

summer stump
summer stump
#

Wait.. so all the objects are in the exact same position?
The three buttons under the canvas I mean?

queen adder
#

Under Main?

summer stump
#

They both at least have the same z position

queen adder
#

No, they're next to each other.

summer stump
queen adder
queen adder
summer stump
# queen adder yes 🙂

So... yeah. That is weird. I assumed they were blocking each other from the beginning, but they aren't even overlapping...

Try using a different tool

summer stump
#

Click the hand, or transform tool

queen adder
#

The hand tool is to move the scene around, the transform tool is to resize, i can't do that without selecting the ui buttons first.

astral basin
#

only s and d work, any idea what i did wrong? thanks

summer stump
#

Did you try the others?

summer stump
astral basin
#

how do i capture input in update and the addforce in fixedupdate? they have to be in an if statement in the same function no?

gaunt ice
#

you can addforce in update

summer stump
astral basin
queen adder
summer stump
#

Only thing I can think is that you need the event system? Shouldn't need it for just selecting in the editor... but may as well try

summer stump
queen adder
summer stump
summer stump
# gaunt ice you can addforce in update

Are you sure about this? I mean... Impulse mode sure, but for constant addforce as the main movement... it just seems not right

Everything I see says no. And I have personally had issues with that in the past

gaunt ice
#

yes, only instant velocity change can be applied in update....

summer stump
#

~~Using AddForce as the main movement (applied every cycle) absolutely should go in FixedUpdate

It of course CAN go in Update. It just SHOULD not~~

#

I think I misunderstood your response

gaunt ice
#

if the change is derived by dt then it should be handled in fixed update though i think you still can simulate it update

topaz mortar
#

Eh? Dunno what is happening here

Debug.Log("2: " + characterHealthRegenPercentage);
Debug.Log("3: " + (character.MaxHealth / 100 * characterHealthRegenPercentage));```
#

how is 40 / 100 * 10 = 0?

#

is this some sort of int/float conversion issue?

charred spoke
#

Yes

topaz mortar
#

(float)character.MaxHealth / 100 * (float)characterHealthRegenPercentage)
yeah this actually works

#

how do I prevent this? what's the proper workaround?

young warren
rocky basalt
topaz mortar
#

they're all ints, even the result needs to be an int lol

#

I have a Mathf.FloorToInt in the actual calculation

#

int regen = Mathf.FloorToInt((float)character.MaxHealth / 100 * characterHealthRegenPercentage);

rocky basalt
queen adder
topaz mortar
#

the logic behind it is just crazy confusing, well it makes sense
but this will probably cause some more issues in the future

rocky basalt
queen adder
#

Okay, seems like I needed to add Raycaster to the parent for some reason to finally click on buttons

topaz mortar
timber tide
#

I'd just make health a float and round it up after adding any modifying operations to prevent truncating too many values.

languid spire
#

@topaz mortar Why dont you simply do

(character.MaxHealth * characterHealthRegenPercentage) / 100;
fringe plover
#

!code

eternal falconBOT
topaz mortar
fringe plover
languid spire
#

int out of range is very large indeed, unlikely you would reach it

topaz mortar
#

probably

keen dew
fringe plover
#

ok, thanks

ivory cypress
#
 private void LateUpdate()
 {
     lifebarCanvas.LookAt(this.transform.position + Camera.main.transform.forward);
 }

I am using a simple lookat function to let my hp bar look at the camera in the late update. However, I find that the hp bar become kind of "broken" (red arrow) when the enemy is moving. How can I fix it?

timber tide
#

Try sticking it in update

vale mountain
#

how do i animate a line renderer? i want it to wobble as it moves like its coming out of a grappling gun

ivory cypress
#

Tried in update. It become worse as the hp bar is shaking when enemy is moving

faint sluice
#

That way it will always face the camera and no need to implement look at

ivory cypress
faint sluice
ivory cypress
#

I have searched tutorial before but he's in 2D

timber tide
#

I do most* billboarding stuff through vertex shaders and using screen position over using camera position

#

overlay canvas sounds like a nice alternative

ivory cypress
#

I am trying right now

faint sluice
# ivory cypress I am trying right now

Create a healthbar for your player character in Unity. Bonus: I'll show you how to smoothly animate the remaining health to give it some cool points!

p.s Sorry about the crappy audio on this one!

❤️ Become a Tarobro on Patreon: https://www.patreon.com/tarodev

=========

🔔 SUBSCRIBE: https://bit.ly/3eqG1Z6
🗨️ DISCORD: https://discord.gg/tarode...

▶ Play video
mystic oxide
#

is it possible to get gameobject -> component from another scene? this really annoyed me for the past few day since i started unity

timber tide
#

You can make the gameobject a prefab and instantiate it on another scene, or if you previously were on that scene you'd use don't destroy on load when loading the new scene to carry it over.

faint sluice
mystic oxide
#

script

fringe plover
#

you can save data on computer and when scene loaded it will load data from computer (lot of code)

mystic oxide
#

trying to access gameobject script from that "current scene" scene

queen adder
#

Could someone help me with the scrollview thing? It returns to original position and the contents inside even go out of bounds

fringe plover
#

whats wrong i dont understand
if (Input.GetKeyDown(KeyCode.E) && inShop == false && near)
{
inShop = true;
}

#

when i put only Input.GetKeyDown(KeyCode.E) it works, but when i add bools it doesnt work

timber tide
#

Object reference is null

fringe plover
timber tide
#

log what you're accessing

fringe plover
#

this is not my script, its unity

mystic oxide
timber tide
# fringe plover

Oh, huh. Sounds like a googling, maybe even try restarting the editor.

fringe plover
#

it worked, but after some time it just stop, yeah ill try

#

nothing changed

#

great, when i removed bools it doesnt even work

timber tide
#

Only other thing I can think of is you were working on some asset and deleted it, but the editor is continuing trying to access it

fringe plover
#

i think i know how to fix it

#

fixed

#

i put code on line 37 (it was on line 21) and it fixed somehow

mystic oxide
#

im sorry but is this the right way to do it, i tried only using 1 audio source, ofc it doesn't work catto

fringe plover
modest dust
fringe plover
#

when i replace them, they are working

queen adder
#

Why can't i move a panel with in a scrollview?

modest dust
vale mountain
# mystic oxide im sorry but is this the right way to do it, i tried only using 1 audio source, ...

it works, but i like to use a class called Sound which has all the properties of an audioSource, then in an AudioManager script having an array of Sounds and having them be accessible in the inspector. then later in the AudioManager script it adds an AudioSource for each Sound in the Sound[]. its exactly the same thing as your doing it just makes it a little easier on the eye when not in play mode

fringe plover
mystic oxide
modest dust
fringe plover
#

wut?

desert elm
#

Hm, I have a question
https://gdl.space/ijapalosur.cpp
I want too make the selected unit move to a location that I click, but I am not sure how I should do that, here are the scripts I have so far-

modest dust
# fringe plover wut?

instead of checking if inShop is true or false, just switch these things within the other two if's

#
        if (Input.GetKeyDown(KeyCode.E) && inShop == true)
        {
            inShop = false;
            baarenController.blocked = false;
            controlls.needed = false;
        }
        if (Input.GetKeyDown(KeyCode.E) && inShop == false && near)
        {
            inShop = true;
            baarenController.blocked = true;
            controlls.needed = true;
        }
#

Idk why separate it

short hazel
#

So you need to use else if

modest dust
#

Ah, that's also true ^

fringe plover
#

ill try

queen adder
#

Could someone help me? I'm not able to move the contents inside content. I can neither resize or remove them, it's like they're anchord.

modest dust
#

Maybe you have some script attached which moves and resizes them

fringe plover
merry spade
#

quick question about saving large amounts of data

#

do you have one script that iterates through every script and saves everything and when loading every script gets through functions their data back or does every script save for themselves`?

timber tide
queen adder
#

For now the scrollview is somehow white

timber tide
merry spade
#

hm im not a native speaker what do you mean?

#

you mean if i have an order in what the data should be loaded or saved i should use one big script?

timber tide
#

Meaning that having everything load itself independently may not load data correctly. If for example you've weapons that have modifiers that have be serialized, well you want to load those first before the actual weapons and such.

merry spade
#

ok so One big script and this script spreads the data to every script?

queen adder
#

Is it possible to the background colour of a scroll view and have the background simply be a photo?

timber tide
#

I'd a fan of a general load manager, with smaller sub load/save systems

merry spade
#

load manager?

queen adder
#

Somehow the scrollview is looking white like this, how do i remove that entirely? because the white is supposed to be a sprite background

timber tide
#

Yes, something that executes the bulk of the serialize data first like location, events that been triggered, then load lesser data like inventory.

merry spade
#

hm ok thank you i hope I can do rest by myself 🙂

#

one more question

timber tide
#

But each would be a subsystem too, for example with the weapons again, you need the logic to recreate these specific weapons with the modifiers it had previously.

merry spade
#

If the game updates like i pick up one wood, should i send this data to the save script and if i press save it saves or when i press save the save script should pick the data that i have one wood out of the inventory script?

solemn fractal
#

Hey my friends, how do i create a simple logic to make a game object always go in the direction of another object no matter where the other object goes? like if its an enemy that always go towards the player? tried something like that but it goes to the position the player is just first time and stop.. even in start method. Vector3 direction = _player.transform.position - transform.position; transform.Translate(direction * _speed * Time.deltaTime);

queen adder
#

Does anyone perhaps know how to remove the white background of a scrollview?

timber tide
# merry spade If the game updates like i pick up one wood, should i send this data to the save...

Depends how frequently you want to serialize that data. Older games you've probably played only saved at points, but arguably that was also part of the difficulty of the game. But nowadays you can pretty much serialize data for every little action you do in case a player's game does crash. But, to keep it simple for now, I'd suggest just serialize the data when the player prompts, or perhaps write the data in increments between scenes, ect.

merry spade
#

when the player "promts"?

#

what do you mean

#

when he saves?

timber tide
#

Save button

merry spade
#

ah iok

#

ok

modest dust
solemn fractal
#

oh SORRY it is in update .. i said it wrong

modest dust
#

Either way, read the rest

mystic oxide
desert elm
timber tide
#

ideally you'd want to look into unity's pathfinding

solemn fractal
#

will check .. thank you

desert elm
#

thank you a well

unreal phoenix
#

What is the purpose of having these items in brackets like this?

if ((Object)(object)m_lastAttachBody != (Object)(object)m_lastGroundBody)

ember gate
#

hello guys how can I make my enemy prefab get the right gameobject to follow like when it spawns the gameobject it should follow is missing from the checkbox

unreal phoenix
#

The object in your prefab is probably referencing an asset and not a game object in the scene. Whatever spawns the enemy should tell it what to follow and you should cache that game object to follow in the spawner

solemn fractal
#

hey guys if I use 2 dots like that, what that means? var target : Transform;

keen dew
#

It means that you're looking at old forum posts or tutorials that use Unityscript instead of C#

solemn fractal
#

ty

unreal phoenix
solemn fractal
#

As a beginner things takes like hours just to learn how to move 1 thing or etc.. but i will be resilient hahaha

ember gate
#

can I not declare the gameobject in the start function?

unreal phoenix
ember gate
#

imma send the chase code one sec

#
public class AIChase : MonoBehaviour
{
    public GameObject car;
    public float speed;

    private float distance;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        distance = Vector2.Distance(transform.position, car.transform.position);
        Vector2 direction = car.transform.position - transform.position;

        direction.Normalize();

        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        transform.position = Vector2.MoveTowards(this.transform.position, car.transform.position, speed * Time.deltaTime);

        transform.rotation = Quaternion.Euler(Vector3.forward * angle);
    }
}
#

its from yt but I want to update it with more things that my game needs

unreal phoenix
#

Do you want it to follow the spawner?

#

or the player

ember gate
#

the player

solemn fractal
#

oh it seems more people want to do the same as me now 😛 hahaha amazing

ember gate
#

they just spawn at the spawner locations

unreal phoenix
#

So the spawners should on awake figure out what the player means, like find the player based off of a tag and store that as a variable

#

and then when a spawner spawns an enemy it should do like SpawnThing(player)

ember gate
#

ye but like the spawner only spawns them it doesn't hold any variable of the enemies cause it has an array that randomly chooses which one to spawn

unreal phoenix
#

or you probably do this

void SpawnEnemy() {
  var enemy = Instantiate(EnemyPrefab);
  enemy.player = player;
}
ember gate
#

lemme show u the spawner code too

#
public class EnemySpawner : MonoBehaviour
{
    [SerializeField] private float spawnRate = 1f;

    [SerializeField] private GameObject[] enemyPrefabs;

    [SerializeField] private bool canSpawn = true;

    private void Start()
    {
        StartCoroutine(Spawner());
    }

    private IEnumerator Spawner()
    {
        WaitForSeconds wait = new WaitForSeconds(spawnRate);

        while (true)
        {
            yield return wait;

            int rand = Random.Range(0, enemyPrefabs.Length);

            GameObject enemyToSpawn = enemyPrefabs[rand];

            Instantiate(enemyToSpawn, transform.position, Quaternion.identity);
        }
    }

}
unreal phoenix
#

if you had a GameManager you could store these kinds of variables there to be instantly accessable by any script during runtime

#
var spawnedEnemy = Instantiate(enemyToSpawn, transform.position, Quaternion.identity);
spawnedEnemy.player = player;
#

Like I said, it doesn't matter

#

Usually you make an Init() method inside of classes that are designed to be spawned

#

And you access that after spawning and pass all the variables and it functions identical to a Start() method

ember gate
#

ight thanks imma try to do what u said

unreal phoenix
#

It won't work as is obviously, you'll have to fill the gaps

ember gate
#

ye

#

ik thats what im trying to figure out now

solemn fractal
#

those 2 simple lines should work no? at least logically. I am saying translate to the position of the played in a specific speed but nothing happens.

keen dew
unreal phoenix
solemn fractal
unreal phoenix
solemn fractal
unreal phoenix
#

try adding transform.position to your direction

#

inside of the translate

keen dew
#

No, the Translate method moves it towards a direction. Not towards another position.

lone sable
#

Can anyone point me towards a yaml reader? Importer? Iunno.

I don't have/can't have a object made so.

solemn fractal
keen dew
#

Direction would be (_player.transform.position - transform.position).normalized

unreal phoenix
#

ok then

gaunt ice
#

just p(i)=p(i-1)+p(i-1)*dt=(1+dt)*p(i-1) i=iteration here
so p(i)=(1+dt)^i*p(0)

ember gate
unreal phoenix
#

should fix it

solemn fractal
queen adder
#

How is it that I can scroll out of bounds with the scroll view?

unreal phoenix
solemn fractal
unreal phoenix
#

Vector3 direction = _player.transform.position + _player.transform.forward;

keen dew
queen adder
#

Could someone help me with scrollview? As you can see I scrolled up and it shows up out of the bound, i want it to remain inside all times.

ember gate
solemn fractal
unreal phoenix
gaunt ice
#

oh i misread
p(i)=_player*dt+p(i-1) so p(i)=_playerdti+p(0)

#

and direction vector is (end point-start point).normalized btw

unreal phoenix
ember gate
#

btw its working as I want to

solemn fractal
ember gate
#

hah

#

just found out about the new unity fee system

north kiln
north kiln
static cedar
#

A bit late to the party ngl.

unreal phoenix
#

does anyone know if a mesh collider on something like this wedge would be horribly expensive?

north kiln
#

Profile it and find out. And as I just said, this is a programming channel.

solemn fractal
#

I asked chatGPT and he gave me the same thing i did before but doesnt work.. hahaha.. chat GPT is dumber than me

#

even tho it moves to the player but to the first position .. its like it is not inside update checking every frame and chaging it..

keen dew
#

If it moves correctly to one position then the only explanation there is that the target is not the player but some other object in that location

solemn fractal
#

there is just 2 objects in the scene.. player and enemy and I have the player there in the enemy so i can access it from the enemy script

keen dew
#

I'm guessing that when the player moves you're not moving the main Player object but a child object inside it

solemn fractal
#

the main camera is inside the player and the script that i use to move is inside the player

keen dew
#

So this script is on the camera?

solemn fractal
#

no on the player

#

I am trying to make the scene and script as simple as possible but even tho as simple as it looks doesnt work hahaha.

keen dew
#

What does SpawnManager do?

unreal phoenix
#

Does the player move at all on start?

solemn fractal
#

nothing yes just created an empty SpawnManager

#

as I thought that would be easy to move the enemy to the player and than i would create the spawn system

#

i know how to create the spawn system but i am stuck to the first part hahaha

#

that is move the enemy to the player hahaha

unreal phoenix
#

Its moving to origin because you are not adding it's postilion in the translate

solemn fractal
#

transform.Translate(MoveDirection * _speed * Time.deltaTime); in this line?

keen dew
#

No, that's fine. Show the same video but have the player object visible in the inspector

unreal phoenix
#

Try adding Space.relative after delat time inside the brackets

#

transform.Translate(MoveDirection * _speed * Time.deltaTime, Space.Self);

#

although it does that by default

solemn fractal
#

it doesnt allow me

swift crag
solemn fractal
#

with the player selected

keen dew
#

I think I know what it is

unreal phoenix
#

is the player ref becoming null on runtime?

swift crag
#

Space.World

keen dew
#

You've dragged the player prefab to the target field, not the player object in the scene

swift crag
#

Aha. That would do it.

solemn fractal
#

space.world same result

swift crag
#

In this case, it doesn't matter, because the enemy is not rotated

#

If the enemy was rotated, it would matter.

solemn fractal
swift crag
solemn fractal
#

YEAh

#

THAT WAS IT

#

HA AMAZING

swift crag
solemn fractal
#

thank you everyone you guys are awsome

keen dew
#

It was looking at the prefab which doesn't move

swift crag
#

Unity won't turn that prefab reference into a reference to the specific instance of the prefab

#

You should definitely add Space.World while you're fixing things, though

#

If the enemy is ever rotated, then its local directions will no longer match the world's directions

#

So if it wants to move to the right, but it's rotated 90 degrees, it'll move vertically instead

solemn fractal
#

got it thank you

swift crag
#

I would normally just do transform.position += ... to directly move an object in a world-space direction

#
transform.position += foo;
transform.Translate(foo, Space.World);
#

these are equivalent

solemn fractal
#

hmm ohh nice ok got it.. thank you

swift crag
#

You know, one thing I don't know is whether transform.Translate takes scale into account

unreal phoenix
#

I don't think it needs to

swift crag
#

Does it just change the direction?

#

let's find out

verbal dome
unreal phoenix
#

I doubt it scales the position

verbal dome
#

My bet is on not-scaling too

swift crag
#

Oh right, even transform.localPosition += foo wouldn't care about the transform's scale

#

I was thinking about it all the wrong way

#

The more interesting thing would be how parent scale affects it

solemn fractal
keen dew
#

Space.Self uses some internal method

swift crag
#

aeugh

#

Okay, yeah, it strictly changes the direction

keen dew
#

but I can't imagine scaling would affect it differently depending on space

swift crag
#

If your parent is scaled to 10x, transform.Translate(Vector3.forward) changes your local Z by 0.1

#

I was wondering if these were equivalent

#
transform.localPosition += foo;
transform.Translate(foo);
#

the anwer: no!

solemn fractal
#

Now I have another question.. If I apply the changes now to my enemy prefab.. and i drag a new enemy into the hierarchy, it doesnt have the player there anymore.

swift crag
#

Right.

#

That's a scene object reference.

#

Prefabs can't reference scene objects.

#

what if the prefab was created in a different scene?

solemn fractal
#

hmm.. so how to fix that when i want to spawn enemies ?

swift crag
#

You will need to do something to tell the enemy about the player

#

One easy option: have the enemy find an object of type Player

solemn fractal
#

oh ok.. like refering it inside the code and not using the inspector

#

ok got it

#

will try

swift crag
#
player = FindObjectOfType<Player>();
#

Another is to put an enemy spawner in the scene

#

and then have the spawner reference the player

#

then the spawner can tell the enemies it spawns about the player

swift crag
#

Searching the scene for objects is relatively slow, and it's also prone to errors

#

maybe not in this case, because there's gonna just be one player

#

but if you ever go from "one of X" to "many of X", that sort of code can cause undesirable results

solemn fractal
#

ok got it will try, thank you !!

#

yea its working as intended thank you !!

#

now I can just drag the prefab enemy and it works

#

so now I can start the spawns.. 😄

#

Sorry guys i know a lot of questions haha - managed to spawn it after 5 sec but it spawns non stop instead of doing it once and waiting 5sec.. what could be wrong here?

keen dew
#

Update runs every frame so you're starting a new coroutine every frame

solemn fractal
#

damn make sense..HA didnt think about it.

#

ok done it like that and worked.

swift crag
#

I would do something like this

#
IEnumerator SpawnRoutine(float interval) {
  while (true) {
    yield return new WaitForSeconds(interval);
    // spawn logic
  }
}
solemn fractal
#

Guys, I am using [SerializeField] and a variable below.. in player and enemy script works and I can see in inspector.. but created another script called bullet and it doesnt work there cant see in the inspector any idea?

desert elm
#

Will
Vector3 positionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Just make a variable that stores the coordinates of the mouse?

swift crag
#

There's a bit of a "gotcha" with that for perspective cameras.

swift crag
solemn fractal
swift crag
#

your changes will not show up in the editor until the code is compiled

#

your code can't compile if there's even a single error

#

I don't know what that means.

solemn fractal
#

Question. I have a method in my script Bullet, and inside the player but not managing to access this method from the bullet inside the player. any ideas?

swift crag
#

look at your types.

solemn fractal
swift crag
#

private GameObject _bullet

#

_bullet is a variable of type GameObject

#

so it can hold a reference to any game object

solemn fractal
#

yes

swift crag
#

GameObject does not have a method called Move.

#

It doesn't matter that the object you are referencing happens to have a component that has a method called Move

solemn fractal
#

but the gameobject BUllet has it and its here

swift crag
#

the _bullet variable is referencing a GameObject.

#

Try dragging other stuff into the field.

#

Any object will work.

#

So there's no way you can call Move on _bullet.

#

I need you to understand that before I show you how to fix it

#

it's pretty important

solemn fractal
#

ok wait I am trying to understand it, give me some seconds

#

but if I am dragging the object Bullet that contains the script Bullet and inside that script I have the method

#

why cant I access it?

swift crag
#

let's clear up some terms here

#

you have a game object named "Bullet"

#

the game object has a component called "Bullet" attached to it

#

these are two completely unrelated things

#

the game object could be named anything

#

the "Bullet" component has a method called Move on it

#

If you have a variable of type Bullet, then you can call Move on it.

#

But you don't have a variable of type Bullet.

#

You have a variable of type GameObject.

solemn fractal
#

ohh so I would need in this case to use

#

a getcomponent maybe?

swift crag
#

The C# code has no way of knowing this object has a Bullet component on it, and that you meant to talk to that component

#

It just sees you trying to call Move on a GameObject and gives you an error.

solemn fractal
#

like bullet = getcomponent<Bullet>(); and with that I can access?

swift crag
swift crag
#

But that's wrong. You should only be able to put bullets in there.

#

So, change the variable's type to Bullet.

solemn fractal
#

ok

swift crag
#

Now the variable will reference a Bullet.

solemn fractal
#

now worked, using the Bullet _bullet and now I understand

#

because using type GameObject can be anything and i was not saying WHICH one

swift crag
#

If you drag a game object with a Bullet on it into the field, Unity will grab the Bullet component off of it and store it in the field.

solemn fractal
#

i wanted even putting the prefab there on the inspector

swift crag
#

And if you Instantiate that variable, it'll clone the entire game object

solemn fractal
#

yeah ok, understood, that was an amazing explanation, thank you for that and your time explaning it 😄

swift crag
#
public Bullet _bullet;

void Update() {
  Bullet instance = Instantiate(_bullet);
  instance.Move(...);
}
#

I almost never use GameObject variables

#

I always want something more specific than any GameObject

swift crag
#
public ListEntry : MonoBehaviour {
  public Image image;
  public TMP_Text text;
}
#

and then I'll reference a ListEntry instead of a GameObject

#
foreach (var item in inventory) {
  ListEntry entry = Instantiate(entryPrefab);
  entry.image.sprite = item.icon;
  entry.text.text = item.label;
}
#

much nicer than

#
foreach (var item in inventory) {
  GameObject entry = Instantiate(entryPrefab);
  entry.GetComponentInChildren<Image>().sprite = item.icon;
  entry.GetComponentInChildren<TMP_Text>().text = item.label;
}
#

and if I add more stuff to the prefab later, my code doesn't break

swift crag
#

a little tweak to the prefab can make everything stop working

#

Pretty much every prefab I make has a component that ties it together

dry tendon
#

Hi everyone, i have a problem on detecting the animation length by code... This code is supposted to do that... But it shows me 1 on the log, but the anim is quite shorter than that. This is the code and the animation length: ```cs
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

public class LoadingScreen : MonoBehaviour
{
private float loadingCanvasTime = 2.4f;

[Header("Drag")]
[SerializeField] private GameObject loadingCanvas;
[SerializeField] private Animator loadingCanvasAnimator;
[SerializeField] private Animator loadingTextAnimator;

void Start()
{
    loadingCanvas.SetActive(true);
    StartCoroutine(CanvasTextFade());
}

private float time;
private IEnumerator CanvasTextFade()
{
    loadingTextAnimator.SetTrigger("ActiveLoadingFadeText");

    yield return new WaitForSeconds(loadingCanvasTime);       
    loadingCanvasAnimator.SetTrigger("ActiveLoadingCanvasFade");

    time = loadingCanvasAnimator.GetCurrentAnimatorStateInfo(0).length;
    Debug.Log(time);

    yield return new WaitForSeconds(0.3f);
    loadingCanvas.SetActive(false);
}

}```
I have to say that all anims are on the deffault layer, i have not touched that. On the next image you can see the log and the anim duration

wintry quarry
solemn fractal
#

hmmmm ok. so now changing the variable name I am able to access the method. But on this script here from the bullet I am doing the same but when I click the mouse button it gives an Object reference not set to an instance of an object. I need to also here put like _enemy = getcomponent<Enemey>(); to work?

swift crag
#

getting an XY problem vibe here

swift crag
swift crag
solemn fractal
#

not variable name sorry variabgle type

swift crag
#

If you changed the type, the inspector could show a reference, but actually be invalid.

solemn fractal
#

I did it but its funny

#

it has the script simble there

#

and not the prefab even doing it again

dry tendon
swift crag
#

you don't need to rename anything here...

dry tendon
#

I've already said that... I want to check by code the length of an animation... But i like to say more details

swift crag
#

You get the prefab icon if you're referencing another prefab

desert elm
#

Why is this throwing up an error?

#

oh I see

#

nvm

charred spoke
#

!ide

eternal falconBOT
swift crag
#

actually, you might still just get the script icon when referencing another prefab. i am unsure

solemn fractal
#

I click there on the right and it says its the prefab but its not

swift crag
#

Why is Bullet referencing the Enemy prefab?

#

Watch the Profiler for big spikes. You might have code that misbehaves when the time per frame is varying.

solemn fractal
swift crag
#

I imagine going frame-by-frame winds up getting rid of some of the randomness from editor code

swift crag
#

Referencing the prefab isn't helpful. It's the same problem you had earlier.

solemn fractal
#

I am for 6h ctrying here just to move the enemy towards the player and do those things that my mnd isnt work.. i might need to eat something hahaha

swift crag
#

It's more productive to take breaks

#

I came up with a big improvement for my settings system while making coffee this morning

desert elm
#

what does this error mean

ivory saffron
#

I have an inherited variable I want to downcast once instead of every time i need it. I could make a new one but i want to reuse code. what should i do?

swift crag
#

you could add a property that performs the cast

#
protected Parent foo;
Child myFoo => (Child) foo;
swift crag
solemn fractal
#

Can i instantiate like that if I am inside the gameobject script? Instantiate(this.gameObject, new Vector3(_player.transform.position.x, _player.transform.position.y, 0 ), Quaternion.identity);

swift crag
#

This would make a copy of the object the component is attached to

solemn fractal
#

i am trying to make when I click i shoot the bullet toward the player but I am getting a object reference not set to an instance of an object. always that error I might not fully understand yet this references .. always had problems that in the past in other stuff hahaha

desert elm
swift crag
#

okay, nothing there looks alarming to me

swift crag
desert elm
#

so . . . I do not have an error?

swift crag
#

Something is wrong, but it doesn't look like the code you shared should be causing any issues.

#

When do you get this error?

swift crag
solemn fractal
#

i tried to remove this part from the bullet script and put in player script where I call it, but it spawns but doesnt move..

swift crag
#

you are trying to move the prefab again

solemn fractal
swift crag
#

Instantiate returns the new instance

solemn fractal
#

ahh

desert elm
swift crag
#

on recompile? when you start playing the game?

desert elm
#

on recompile yes

swift crag
#

get_main sounds like you're trying to access Camera.main

#

obviously that's not the case in the code you shared

solemn fractal
swift crag
#

I think you should compute the direction the bullet should go in

#

and tell the bullet about that direction

#

then the bullet can move itself in its Update method

swift crag
# solemn fractal

this code is also not correct. the bullet's world-space position will change based on where your mouse is

#

But the mouse's position is measured in pixels from the bottom left corner

#

That has nothing to do with the bullet's world-space position

#

You need to use Camera.main.ScreenToWorldPoint to get the point in the world your mouse is hovering over

#

I would suggest doing it like so:

#
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = transform.position.z; // so the bullet doesn't fly out of the screen!
Vector3 dir = mousePos - transform.position;

bullet.direction = dir;
#

dir is a vector pointing from the player's position to the mouse's position

#

The bullet can then use direction to move itself every frame

tall delta
# desert elm on recompile yes

from what I can gather it seems like you are trying to do something like this:

public class MyClass {
    // init fileds
    vector3 someVar = SomeUnityObject.Main; // <- auto init the variable with a unity variable
}

this is not allowed and you need to do it an awake, start, etc

public class MyClass {
    // init fileds
    vector3 someVar;

    public void Awake() {
         someVar = SomeUnityObject.Main; // <- init here
    }
}
swift crag
#

you would want to normalize the vector

swift crag
solemn fractal
swift crag
#

But I ain't seeing it in that code

swift crag
desert elm
#

Oh now the error is gone

solemn fractal
#

ok thank you

swift crag
ivory saffron
#

I have classes Weapon : Item, WeaponController : ItemController. ItemControllers have static methods that instantiate and return a controller. This method is called from virtual Item class method. so Weapon does this for WeaponController. but i cant reuse code in controllers because of different types. the static init method cannot be overriden at all. I need inheritance to keep the ItemController reference. How should i approach this?

twin ember
#

Given an alpha map image texture, how to I apply it to a material?

swift crag
#

ah, inventories

#

the one place where I wind up doing downcasting a lot

swift crag
#

But then you couldn't just store an ItemController

#

you'd have to specify the generic type. no dice.

#

hm, how have I handled this in my own game..?

#

I mostly just work with specific kinds of items.

#

So I have types for weapons and consumables, notably

#

The top level item type doesn't have a method to create an instance of the item

#

The derived types do.

#

e.g. in my InventoryMeleeWeapon class:

    public Weapon Create()
    {
        Weapon weapon = GameObject.Instantiate(spec.prefab);
        weapon.spec = spec;
        weapon.Setup();
        return weapon;
    }
#

I don't have a Create on InventoryItem.

#

You can't do covariance, unfortunately

#
public class Foo { }

public class Bar : Foo { }

public abstract class Parent
{
    public abstract Foo Gimme();
}

public class Child : Parent
{
    public override Bar Gimme()
    {
        return new Bar();
    }
}
#

This is a compile error.

#

This would be convenient because calling Gimme on a variable of type Child would return a Bar, not a Foo

ivory saffron
#

maybe i could make the static init method generic and only in the top class, other things i need to process

swift crag
#

Inventories are often a type fiasco

#

I struggled with this a lot

#

(and I still am!)

tall delta
swift crag
#

Yeah, that's basically what I've wound up doing

desert elm
swift crag
#
    public T ItemAt<T>(int index) where T : InventoryItem
    {
        if (typeof(T) == typeof(InventoryMeleeWeapon))
            return meleeWeapons[index] as T;
        if (typeof(T) == typeof(InventoryRangedWeapon))
            return rangedWeapons[index] as T;
        if (typeof(T) == typeof(InventoryBodyWeapon))
            return bodyWeapons[index] as T;
        if (typeof(T) == typeof(InventoryConsumable))
            return consumables[index] as T;

        throw new Exception("bad item type");
    }
#

I don't like it...

solemn fractal
#

its working now .. it goes where the mouse is, but it follows the mouse instead of just going straigh line to where the mouse was when I clicked. But I will eat something and try to figure it out this.. thank you a lot !!

tall delta
desert elm
#

Right, the code to select a unit worked before, but now it does not- what mistake did I do?

tall delta
desert elm
#

thanks

frosty hound
desert elm
swift crag
#

I would suggest writing your own code.

frosty hound
#

If you want to try to get the basics of how code works there are tutorials pinned to this channel.

desert elm
desert elm
solemn fractal
#

Is there a way to do something like that, like that?

#

i mean i see its not possible like that so how would be the correct way ?

swift crag
#

Why are you making the bullet instantiate itself?

#

That doesn't make any sense.

#

but for the cause of the error: Instantiate(this.gameObject) returns a GameObject, because you gave it a GameObject

#

Instantiate(this) would return a Bullet

solemn fractal
#

trying to follow some stuff I see in the internet to fix my prob..

#

the guy in the video does like that and works for him

swift crag
#

bulletPrefab is probably a GameObject here

#

he stores it in a GameObject variable

solemn fractal
#

it seems i need to use rigid body to shoot stuff like i want

swift crag
#

var automatically determines the type of the variable

#

He then gets a Rigidbody2D component from the instance

solemn fractal
#

GameObject i tried but also doenst work

swift crag
wintry quarry
#

Oh it works fine

swift crag
#

you need to stop and think about what the Bullet class is supposed to do

#

I don't think its job includes "make copies of itself when it moves"

wintry quarry
#

But yeah why is it instantiating itself

swift crag
#

you can't just put code in random places

#

you must do everything with clear intent.

solemn fractal
#

well.. i am trying, if I knew how its done and where to put stuff I would surely have this done already 😛

swift crag
# solemn fractal

Don't just look at these few lines of code. Look at where they are, and when they run

wintry quarry
# solemn fractal

This is a script that shoots bullets.

It's not the bullet script itself. More like a gun script

#

Pay attention to the tutorial

#

Or whatever you're reading

swift crag
#

you can write a perfectly valid line of code and still get bogus results

#

because the code is in the wrong place at the wrong time

solemn fractal
#

now I am using it on the correct place that is why its working

swift crag
#

you're setting the velocity based on the bullet's position

#

if the bullet is at [3,4], then its velocity will be [6,8]

solemn fractal
#

damn, i wish I could see stuff like u that fast my mind is so slow yet to process info

#

hahaha

swift crag
#

I am thinking about the meaning of each variable.

#

Position and velocity are different concepts

#

So it's suspicious to see them getting mixed together like that

#

You need to get the world position of the mouse, then subtract the player's position from that

#

This will give you a vector pointing from the player to the mouse

#

This is the direction the bullet should move.

solemn fractal
#

but how do i set here a fixed velocity? if I put just a number it doesnt accept. bullet.GetComponent<Rigidbody2D>().velocity = transform.position * 2;

swift crag
#

well, stop using transform.position first

swift crag
solemn fractal
#

still try like that

swift crag
#
Vector3 dir = Vector3.right * 3;
Foo(dir.normalized);
solemn fractal
#

worked 😄

swift crag
#

this would call Foo with a [1,0,0] vector

#

A normalized vector has a length of 1.

pallid verge
#

In this script right here if i hold the Jump button will "hasJumpedThisFrame" stay true or will it turn false at the start and then true when it recognizes that im holding Jump?

swift crag
#

It will be set to true every frame that you're holding the jump button

pallid verge
#

Because in the Console it says that it stays true

swift crag
#

It will indeed be set to false at the start of Update

pallid verge
#

alright thank you

swift crag
#

But then it'll immediately get set to true.

swift crag
#

Were you expecting it to show up as false in the console?

pallid verge
#

I was expecting it to cycle between true and false but now when i think about it that doesnt make sense

swift crag
#

yeah, there's nothing that would make it fail that conditional every other frame

#

You'd only see "false" if you logged it somewhere in the middle.

pallid verge
#

yeah i was logging it at the end lol

swift crag
#

(and then you would only see false)

fast knot
#

I have a really basic question: When i should use the Update() method and when the FixedUpdate() method?
I know the difference but i have no clue when i should use the one or the other..

swift crag
#

FixedUpdate is run once per physics update. Update is run once per frame.

#

FixedUpdate should be used for things that affect physics. This keeps physics consistent even as your frame rate changes.

#

Update should be the default.

young warren
# fast knot I have a really basic question: When i should use the Update() method and when t...

Check out the Course: https://bit.ly/3i7lLtH


Learn how to move things properly with Update and FixedUpdate. We'll discuss the differences between them, why you should read input in Update and why you should move in FixedUpdate. We'll use a ball hitting dominos as an example of a character we can control and move around using wasd and...

▶ Play video
fast knot
#

Thank you guys!
So as soon as physics are involved FixedUpdate() is the way to go

quasi rose
ruby python
#

Not sure if this is the correct place, but I've had a notion and was just wondering if it were possible. Is it possible to get the position/rotation/scale of a VFX Graph particle based on the position of the player and replace said particle with a prefab (and vice versa).

spare mountain
ruby python
#

Distance from player sorry.

harsh owl
#

currently working on the controller and physics for my "hover car f-zero type controller", my main problem is moving on things like this ramp, instead of smooth movement like moving on the normal floor it kinda goes up like on stairs. Anyone got an idea how i could fix that or maybe a better way of doing it than im doing it right now? thanks

btw im not using gravity on my rigidbody right now

swift crag
#

well, you move the car up or down whenever the height difference exceeds a threshold

#

Are you trying to make it so that you smoothly rise up and fall down, instead of instantly snapping to the right height?

harsh owl
#

yep

swift crag
#

In that case, instead of checking if the difference is too large and setting your position, you should just move a little towards the correct height every update

#

I would move towards the right height with at least a base constant speed

#

and then also increase the speed if the difference is large

#

I see that you have this restoreHeightSpeed variable

#

so maybe you're already trying to do it?

harsh owl
#

yea

#

but it works kinda goofy

swift crag
#

what if you just get rid of the conditional?

harsh owl
#

if(Mathf.Abs(heightDifference) > 0.1f)

#

that one?

uncut dune
#

guys could u give me a hand rll quick

#

basically what Im trynna do is this:

#

and it works sometimes

#

problem being

#

Im using raycasts

#

and what I do is after my raycast hit the wall

#

it will calculate a vector

#

and change diretion

slender nymph
#

please finish your thought before pressing enter

uncut dune
#

making so that it creats a new line renderer to show the deflected, the problem I have is that the raycast sometimes gets the origin point from the wall and collides with the same wall making it stop there and spawn all the next bounces in that same place

#

like this

#

any idea on how I could fix it?

slender nymph
#

you still haven't shown your code so how could we guess what you need to do to fix it?

uncut dune
#

this is where it deflects

#

!code

eternal falconBOT
uncut dune
#

this is the part of the code that is doing all that, I will try and divide it into smaller functions but for now Im trying to make it work as it is

slender nymph
#

hit.point-wallPos why this and not just the direction of the raycast?

uncut dune
#

I'll change it

verbal dome
#

For example, hit.point + rayDirection.normalized * 0.001f

uncut dune
uncut dune
#

wouldnt I want to make it slightly before?

verbal dome
#

rayDirection is the direction of the next ray here

#

You get the point tho

#

Offset it outwards a bit

#

You can either use the ray's direction or the last hit's normal as the offset

harsh owl
verbal dome
#

Red is the first ray, yellow is the offset, blue is the second ray, does it make sense? @uncut dune

uncut dune
#

I thought u were saying to using the offset in the last raycast

#

making the hitpoint a little behind

uncut dune
#

THANK YOU SO MUCH

verbal dome
#

Noyce

uncut dune
#

great work

thorny abyss
#

Hi All - quick general question. Are hashtables a good method for enemies in games? I.e. to keep a certain number on screen and destroy the gameobjects at certain times. Or is this just unnecessary complication?

tall delta
dry tendon
#

is there any way in unity to detect current time on your android device? or i have to use an API?

thorny abyss
#

haha! I'm part way through a game with my brother. I'm quite new to coding. We've ended up using hashtables in our code for gameobjects and I'm finding it a nightmare to work with. Wondering if there is really any benefit to them. I feel like I'll have a bit more freedom and make things simpler without them

verbal dome
dry tendon
thorny abyss
#

I think it came from some random procedural generation code. The game is random as it progresses. So say there's platform tiles. Only ever 6 at a time, anything the players already passed get's destroyed and a new tile put at the front... so it can go on infinitely.

#

That method has then passed across in gameObjects like enemies and moving scenery etc. It works well for the random generation of tiles but I'm just thinking is it really a good idea for enemies? When I could just destroy the enemies of screen once the player has passed them using x values

verbal dome
#

You are asking is it good idea to use X without providing a reason to use X in the first place

slender nymph
#

it's better to reuse the enemy objects rather than destroying and recreating them. however hashtables aren't really necessary for pooling objects like that.

thorny abyss
#

ah... reusing sounds like a good approach

slender nymph
#

of course you haven't even shown any code or actually explained how you are using the hashtables or even whether it is the actual HashTable type or the generic version which would typically be better

thorny abyss
#

yeah was trying to keep it generic

fast knot
#

What is the correct way to use the AddTorque function?
I am currently using Time.deltaTime and someone wrote that's not the correct way to do it (but it work's) 🧐

frontTire.AddTorque(breakingForce * Time.deltaTime);
backTire.AddTorque(breakingForce * Time.deltaTime);

Regarding to the docs https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddTorque.html i am not rly sure if that's a problem as long as it works in my usecase. Any opinions?

slender nymph
thorny abyss
#

haha true

tall delta
slender nymph
verbal dome
thorny abyss
fast knot
#

So the "Impulse" example at docs is what i should do?

swift crag
#

and yes, it'll function

#

but it'll be wrong

#

the amount of force applied will wind up depending on your framerate.

#

or, if you put it in FixedUpdate, the amount of force will just wind up getting divided by 50

swift crag
#

Just apply torque. That's it.

empty radish
swift crag
#

AddTorque tells the rigidbody you're twisting it with a certain amount of torque

thorny abyss
#

so say I've got 5 gameObjects in a hashtable. Their x values can move positively and negatively.... I want to find x values on each update which are behind the player so I can destroy the game object and free up space in the hashtable for new ones to be created via the code already there. Right now I've managed to get the x values of all the game objects currently in the hashtable on screen. I was goingt o then create an array of these x values, then find the one's less than or behind the player to then destroy them. Problem I have is I don't know how to translate from the x values in the array to the gameobjects in the hashtable so as to be able to destroy them

slender nymph
#

the hashtable is irrelevant here. also you're still not providing concrete details on how you are actually using the hashtable if that is your concern

swift crag
#

it's just...1 newton, constantly.

fast knot
swift crag
#

Every FixedUpdate, yes.

thorny abyss
swift crag
#

Then we can't help you.

#

Share your code.

thorny abyss
#

hahahaha fair enough

fast knot
# swift crag Every FixedUpdate, yes.

One (last) question regarding to the AddTorque topic. What's the common way to limit the objects speed?
Like right now if you press a button the car is always getting 10 torque and is accelerating like a rocket.

swift crag
#

In real life, friction and air resistance (especially air resistance!) both increase as you go faster.

#

Try adjusting the drag on your rigidbody

#

If that makes the car feel too stiff at low speed, you could increase the drag as the velocity goes up, or something similar

#

video games can cheat with physics

slender nymph
#

you can also clamp the angularVelocity if you just want a hard speed limit

thorny abyss
#

think I just need to read up on hashtables to get better at understanding how to draw information form them

swift crag
slender nymph
swift crag
#

since you usually can't modify a data structure while iterating over it, you can make a separate list to put the objects in

#

that's pretty much it.

fast knot
fast knot
verbal dome
#

Hashtable and other non-generic collections seem pretty useless to me anyway

swift crag
#

perhaps they mean Dictionary, yes

#

"hash table" would be a more academic name for the concept

quiet dune
#

About ObjectPool: I want to implement an ObjectPool for instances of a GameObject B, which can be used by multiple instances of GameObject A, but i cant figure out where to implement it so all As can access the same pool

slender nymph
slender nymph
swift crag
#

indeed

#

If every A can use the same pool, then a static field is reasonable

#

But if you might need to have them use different pools, you'll need to hand a reference to each of them.

harsh owl
# swift crag Right.

i remade my code so it moves the position of the hovercar constantly to the desiredposition, but im not sure if its the right way again since my car now jitters mid air:

if (Physics.Raycast(transform.position, Vector3.down, out checkCarHeight, desiredHoverHeight))
{
    Vector3 currentHoverHeight = new Vector3 (0, checkCarHeight.distance);
    Vector3 desiredHoverHeightV = new Vector3(0, desiredHoverHeight);

    
    Vector3 adjustHeightDirection = desiredHoverHeightV - currentHoverHeight;
    rb.MovePosition(rb.position + adjustHeightDirection);
    
    Debug.DrawLine(transform.position, checkCarHeight.point, Color.red) ;
    print(currentHoverHeight);
}


quiet dune
#

@slender nymph @swift crag Thanks guys, I think having a single pool is good, because As spawn Bs in "spikes" and their lifetime is short. I thought that implementing the pool static in B would be a good idea, rather than in A, but stumbled over not being able to drag Bs prefab in a static variable of B...

swift crag
#

Static fields aren't serialized, so yeah

#

One very useful idea is to make a dictionary that maps unity objects to object pools

#

each key being a prefab

quiet dune
swift crag
#

so you say "gimme an instance of this prefab!" and the (singleton) object pool manager sees if it has a pool for that object yet

#

if not, it creates one

#

then it just looks up the pool and asks it for an instance

harsh owl
rich adder
solemn fractal
#

Hey hey, trying to delete the bullet after 5sec, I already have the collision and it destroy when kill enemy.. but if it doesnt hit the enemy i want it to destroy in 5sec.. tried to use IEnumerator or the way it is here in the SS but is not working. Any ideas?

quiet dune
verbal dome
#

If PoolManager is a static class (or 'gimme' method is static) then you would do PoolManager.Gimme() @quiet dune

rich adder
solemn fractal
rich adder
verbal dome
#

If it is a component, you are destroying the component, not the gameobject

quiet dune
#

@swift crag @verbal dome I'll try that approach. Thanks guys

solemn fractal
verbal dome
#

You want Destroy(bullet.gameObject, 5.0f)

solemn fractal
#

oohhhhh

#

true

#

amazing thank you !!

#

I used like that in other script

#

example

#

and didnt notice my own

#

mistake

#

thank you

verbal dome
#

It's a common mistake

rich adder
#

this is reduant here

#

consider CompareTag instead

swift crag
#

(two separate suggestions, btw)

desert elm
#

right so- I assume that
if I click on a game object with this script and there is a unit selected, it will deselect it, right"

wintry quarry
#

You would need some kind of centralized manager to track the currently selected object

desert elm
wintry quarry
#

It should be on the individual selectable things

desert elm
#

Well, the centralized manager is also the map

wintry quarry
#

Seems a little bit of a separation of concerns violation but, sure, should work.

desert elm
wintry quarry
# desert elm

OnMouseDown requires a physics collider. If this is a UI element you shouldn't be using OnMouseDown

#

You should use IPointerDownHandler

desert elm
#

Still doesn't work-

wintry quarry
#

You'd have to show what you did

desert elm
#

oh sorry

wintry quarry
#

Nope

#

That's very wrong

#

It's an interface you implement

desert elm
#

right- okay wait a moment

thorny abyss
#

what approach would people use to randomly move objects around?

#

could you just lerp to random positions over random times

#

could you just lerp to random positions over random times?

quasi rose
charred spoke
quasi rose
#

if it's purely visual background stuff, i'd maybe tween, for example.

thorny abyss
#

it is background stuff yeah

#

but also background stuff that interacts at certain points in the game so lerping to a position near the player character might help me I'm thinking

#

don't know what tween is! Pretty new to coding

desert elm
# wintry quarry It's an interface you implement

I do not understand this part of the guide on interfaces, and how to do so for IPointerClickHandler
How do I declare the interface in this case?
And what are the PointerEventData/are they needed in this case?

quasi rose
terse raven
#

Hi everyone! I'm having a little issue with void Update not being called. Right now I have 1 script with a class as follows "public class Placeable : Monobehaviour" and another script with "public class Generator : Placeable". Inside of the Generator class I have a void Update method which is not being called. I've tested it with debug.log. Can anyone tell me why this is not being called and if so how to fix it. thanks

short hazel
#

This is valid for all Unity messages (Awake, Update, Start, FixedUpdate, etc.)

quasi rose
# desert elm just this?

Sorry I don't have the IPointerClickHandler interface off top of my head. I was explaining more of how IDamageable would work in a general sense.

charred spoke
#

Like SPR told you

quasi rose
short hazel
# terse raven How do I write this in C#?

public virtual void Update() { /* base implementation here */ }
public override void Update() { base.Update(); /* call base class update, then implement derived behaviors */ }

desert elm
quasi rose
short hazel
# desert elm just this?

Also you need to configure your code editor so it highlights errors for you, and gives suggestions as you type

#

!vs

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

quiet gazelle
#

I want to have a character preview in the inventory. Much like in wow / rust / zelda etc. Is there any better way to achieve this than: 1. create a copy of the character model, 2. attach afront facing camera to it, make it render to a render texture, add that render texture to a raw image?

desert elm
#

nevermind now it
can't deselect a unit

Ill work on it tomorow

ripe shard
acoustic arch
#

for the first item put into the inventory it is given 2 automatically instead of just 1

#

i cant find out why

woven moss
#

How do I change whichSprite in
void spawnAsteroidPT2(int whichSprite)
but inside of a function?

acoustic arch
wintry quarry
wintry quarry
#

whichSprite appears to be a parameter to the function

#

you can pass in whatever you want when you call it

woven moss
verbal dome
#

!code

eternal falconBOT
woven moss
#

void spawnAsteroidPT2(int whichSprite)
{
if (//Anything)
{
whichSprite = //Anything
{
}
this isnt working

#

oops

acoustic arch
#

doesnt happen if it goes to the 2nd slot which is weird

wintry quarry
acoustic arch
verbal dome
acoustic arch
#

but it could be stacking it anyway which shouldnt be possible

verbal dome
acoustic arch
#

solved

#

an empty item data was sitting in it lol (actually 2)

woven moss
wintry quarry
verbal dome
wintry quarry
#

you pass it in as a parameter

#

it would accomplish little to change it inside, though yes you can always assign things with =

woven moss
wintry quarry
#

you are giving very few details

#

we can't help this way

woven moss
#

It says "Unnecesary assignment of a value to 'whichSprite'

short hazel
#

Post the affected code

#

Most likely you're referring to the wrong variable

wintry quarry
#

as I was saying

short hazel
#

You put a value in whichSprite, which is not used anywhere, the error says

woven moss
#

void spawnAsteroidPT2(int whichSprite)
{

    if (whichSprite >=1 && whichSprite <= 5)
    {
        GameObject asteroidPrefab = asteroidPrefabs[whichSprite];
        if (whichSprite == 4)
        {
            if (canSpawn4)
            {
                GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
                TheAsteroid = Asteroid;
                AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
                if (Af.collided == true)
                {
                    GameObject.Destroy(TheAsteroid);
                }
            }
        }else if (whichSprite == 5)
        {
            if (canSpawn5)
            {
                GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
                TheAsteroid = Asteroid;
                AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
                if (Af.collided == true)
                {
                    GameObject.Destroy(TheAsteroid);
                }
            }
        } else
        {
            whichSprite = 1; //  DOWN HERE
            GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
            TheAsteroid = Asteroid;
            AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
            if (Af.collided == true)
            {
                GameObject.Destroy(TheAsteroid);
            }
        }
    }
    
}
wintry quarry
#

so you have to explain better what you're tryingf to do

short hazel
#

Doesn't want to read it seems

#

Post code properly

#

!code

eternal falconBOT
eternal falconBOT
short hazel
#

Double kill

woven moss
#

idk how this works

verbal dome
#

Look up how to type a backquote with your keyboard

#

(referring to the code you just deleted)

acoustic arch
verbal dome
#

Depends on your layout/keyboard language

woven moss
#

'''//like this?'''

#
    {
        
        if (whichSprite >=1 && whichSprite <= 5)
        {
            GameObject asteroidPrefab = asteroidPrefabs[whichSprite];
            if (whichSprite == 4)
            {
                if (canSpawn4)
                {
                    GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
                    TheAsteroid = Asteroid;
                    AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
                    if (Af.collided == true)
                    {
                        GameObject.Destroy(TheAsteroid);
                    }
                }
            }else if (whichSprite == 5)
            {
                if (canSpawn5)
                {
                    GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
                    TheAsteroid = Asteroid;
                    AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
                    if (Af.collided == true)
                    {
                        GameObject.Destroy(TheAsteroid);
                    }
                }
            } else
            {
                whichSprite = 1; //THIS
                GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
                TheAsteroid = Asteroid;
                AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
                if (Af.collided == true)
                {
                    GameObject.Destroy(TheAsteroid);
                }
            }
        }
        
    }```
#

ahhh I got it

#

mb im dumb asf

wintry quarry
verbal dome
#

Yep, now add the cs so it highlights C#

wintry quarry
#

you mean to say you want to modify the variable that you passed in as a parameter

woven moss
#

yes

wintry quarry
#
myVariable = myFunction();```
#

and make sure myFunction returns the new value

#

that's all

woven moss
#

ohhh I think I get it now

wintry quarry
#

for exmaple:

int Example(int y) {
  if (y == 1) return 5;
  else return 0;
}

void OtherCode() {
  int x = 1;
  x = Example(x); // now it will be 5
}```
woven moss
#

ty, c# has many rules I need to get used to

verbal dome
#

Now what is the point of that function? I see a lot of duplicate code

wintry quarry
#

indeed

woven moss
#

I still am trying to learn to use parameters tho

woven moss
# verbal dome Now what is the point of that function? I see a lot of duplicate code
    {
        
        if (whichSprite >=1 && whichSprite <= 5)
        {
            GameObject asteroidPrefab = asteroidPrefabs[whichSprite];
            if (whichSprite == 4)
            {
                if (canSpawn4)
                {
                    spawnSpec();
                }
            }else if (whichSprite == 5)
            {
                if (canSpawn5)
                {
                    spawnSpec();
                }
            } else
            {
                whichSprite = 1; //THIS
                GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
                TheAsteroid = Asteroid;
                AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
                if (Af.collided == true)
                {
                    GameObject.Destroy(TheAsteroid);
                }
            }
        }
        void spawnSpec()
        {
            GameObject Asteroid = Instantiate(asteroidPrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
            TheAsteroid = Asteroid;
            AsteroidFunction Af = TheAsteroid.GetComponent<AsteroidFunction>();
            if (Af.collided == true)
            {
                GameObject.Destroy(TheAsteroid);
            }
        }
        
    }```cs

I believe this would help a bit?
wintry quarry
polar acorn
woven moss
verbal dome
#

Might be good to explain what youre actually doing. Are you trying to spawn asteroids with random sprites?

wintry quarry
verbal dome
#

What is spawnSpec? I dont know whats going on

woven moss
#

I think I got it solved mostly

ivory saffron
#

i have methods with the same scripts that i want to combine into one but cant because of types. There are classes B : A and C : A. 1 method: return new B(); 2 method: return new A(). I want to make method 3 that will return new A() that stores B() or C() depending on method parameters. So i want something like a dictionary[key, type]. is it possible?

wintry quarry
#

they run code

#

if B and C both derive from A you can pass them around as if they are of type A

#

If you are having specific trouble with that you'll need to post your actual code and any errors you're encountering

ivory saffron
#

when i said store i meant i need it to return base class instance that stores an inherited one so i can downcast

wintry quarry
#

the base class instance doesn't "store" an inherited object.
You can have a reference of type A that refers to an object of any of the types A, B, or C

#

So using references of type A should work fine

#

If you are having specific trouble with that you'll need to post your actual code and any errors you're encountering

ivory saffron
#

i dont have any troubles i'm trying to make a structure. i think you're misunderstanding the question

wintry quarry
#

I think I am too. I don't understand what you need a dictionary for

#

this is all very XY

#

What are you actually trying to do? Start there

ivory saffron
#

Well i'm not going to ask you how to do class architecture, instead i'm asking a specific question. I need a method that takes a parameter key, instantiates an object of type based on this key (this is why i made a dictionary analogy), then returns base class that this type derives from that references the object. sorry if i cant make it less complicated

wintry quarry
swift crag
#

I can’t follow what you’re trying to do

#

Explain your use case.

#

Although, if I’m reading this right, you do just want a dictionary that maps this parameter to an object

#
Dictionary<SomeEnumType, Foo> options;

public Foo GetThing(SomeEnumType key) {
  return Instantiate(options[key]);
}
#

if this is not what you're trying to do, then you'll need to explain further

dry tendon
#

heey, in need help, but I have to say that is not an easy help one... In the next code, all's correctly working excepting that when there is not internet, it always shows me the log ACTUALMENTE ES DE NOCHE and i don't know why is that appenning cause i've created the JSON file GameData for that... I hope you can help me... I would be really thankfull with you...

wintry quarry
eternal falconBOT
swift crag
#

have you debugged your code to make sure it's actually loading the game data correctly

wintry quarry
#

Of course it's goiong to print that

#

Oh didn't see Sunrise vs Sunset

#

still just print all these values out

#

it should become pretty obvious

dry tendon
#

@wintry quarry what?

wintry quarry
#

use Debug.Log

#

print everything out

#

you will see why it's always true

dry tendon
mossy arrow
dry tendon
#

@wintry quarry like this?

mossy arrow
#

1, 2, 3, and 4 did not work

swift crag