#💻┃code-beginner

1 messages · Page 573 of 1

quick pollen
#

what is the x?

naive pawn
#

the plane exists in 3d, but the plane itself is 2d

#

a plane doesn't have a thickness

languid spire
verbal dome
slate haven
#

But what if i dont know about the height and width? I just wanna fit the no.of blocks on the plane. Every other level would have different amount of blocks. So there shouldnt be any pre-decided width and height right?

naive pawn
quick pollen
verbal dome
#

I'm just being a smartass because you were being one

languid spire
#

yes, it is it is passed to the CreatePooledItem method

slate haven
#

please dont deviate

quick pollen
ivory bobcat
quick pollen
#

why can't you just pass i directly?

naive pawn
# verbal dome I'm just being a smartass because you were being one

In mathematics, a plane is a two-dimensional space or flat surface that extends indefinitely.
the plane itself is 2d
it can be oriented in 3d, that doesn't affect its dimensionality
a line can also be oriented in 3d, but it'd still be 1d
a point can be positioned in 3d, but it'd still be 0d

verbal dome
# quick pollen why can't you just pass `i` directly?

Because i is "captured", meaning that the i passed into the method sort of as a reference and it will actually get incremented in the loop, and when the lambda gets called, i is not the same anymore
So you separate it into another variable to avoid that

quick pollen
#

ohh

ivory bobcat
naive pawn
quick pollen
#
    private void Awake() {
        for(int i = 0; i < projectiles.Count; i++){
            Pools[i] = new ObjectPool<GameObject>(() =>
            { int x = i; return CreatePooledItem(x); }, OnTakeFromPool, OnReturnedToPool,
            OnDestroyPoolObject, true, 20, 50);
        }
        Instance = this;
    }
    GameObject CreatePooledItem(int i)
    {
        GameObject newPooledObject = Instantiate(projectiles[i]);
        newPooledObject.GetComponent<BasicBullet>().pool = Pools[i];
        return newPooledObject;
    }
#

I have this currently

slate haven
slate haven
naive pawn
#

you could define it yourself

naive pawn
#

just define that the base plane is some size and then base your other calculations on that assumption

slate haven
quick pollen
#

it says its out of range

slate haven
#

how do i assume it

quick pollen
naive pawn
verbal dome
#

Yes

naive pawn
languid spire
slate haven
quick pollen
#

and projectiles.Count right now is 1

languid spire
#

so Pools.Length should also be 1

quick pollen
#

ill try to log it

languid spire
#

wait Pools is a List is it not

quick pollen
#

yeah

#
    [SerializeField] List<GameObject> projectiles = new List<GameObject>();
    public List<IObjectPool<GameObject>> Pools = new List<IObjectPool<GameObject>>();
    public static ObjectPoolingProjectiles Instance;
    private void Awake() {
        for(int i = 0; i < projectiles.Count; i++){
            Debug.Log(Pools.Count);
            Pools[i] = new ObjectPool<GameObject>(() =>
            { int x = i; return CreatePooledItem(x); }, OnTakeFromPool, OnReturnedToPool,
            OnDestroyPoolObject, true, 20, 50);
        }
        Instance = this;
    }```
#

I do create it

languid spire
#

no, needs to be an array of length [projectiles.Count]

naive pawn
# languid spire no

if it's inside the lambda, it's not gonna actually do anything, it'll just get the last value of i

#

i just tested this

languid spire
naive pawn
quick pollen
languid spire
verbal dome
# quick pollen

So initialize it elsewhere or use a const for the projectile pool count

naive pawn
naive pawn
#

because it's also used in the lambda

quick pollen
#

well, I'm still having issues with understanding lambdas

languid spire
#
public IObjectPool<GameObject>[] Pools;
```private void Awake() {
   Pools = new IObjectPool<GameObject>[projectiles.Count];
...
quick pollen
#

now
GameObject newPooledObject = Instantiate(projectiles[i]);
is out of range

languid spire
quick pollen
#

yes, thats what I did

#

for some reason i is 1

#

it should be 0

verbal dome
#

Because of what Chris said

naive pawn
#

is projectiles.Count 1 here?

quick pollen
naive pawn
#

yeah the capture is the issue

quick pollen
#

so I should make the x non-local?

naive pawn
#

well it'd still be local

#

just local to a different part

quick pollen
#

well, yeah

#

not local to the lambda, I meant

verbal dome
#

You just move the int x = i before the lambda

quick pollen
#

yeah now it works

naive pawn
#
    private void Awake() {
        for(int i = 0; i < projectiles.Count; i++){
            Debug.Log(Pools.Count);
            int x = i;
            Pools[i] = new ObjectPool<GameObject>(() => CreatePooledItem(x), OnTakeFromPool, OnReturnedToPool, OnDestroyPoolObject, true, 20, 50);
        }
        Instance = this;
    }
quick pollen
#

man, this is getting me kinda brainfucked ngl

naive pawn
#

lambdas are just functions as objects

quick pollen
quick pollen
#

I know what functions and objects are

#

well, objects more or less

languid spire
quick pollen
#

o right true

languid spire
#

inside the for

quick pollen
#

tyty

#

thats just

#

i dont even

naive pawn
#

if you use i directly in the lambda, that's kinda "referencing" the i variable
when the lambda is called, it retrieves whatever i is currently, instead of what i was when the lambda was made
since i changes, the value used when the lambda is called also changes

when you assign a local int x = i; the same situation happens, except that x doesn't change (each loop iteration creates a new x) so the "current" value that's retrieved is the same value when the lambda was made

quick pollen
#

also the fact that I didn't need no Func or Action

verbal dome
#

this is captured because CreatePooledItem is a member of this (your class)

naive pawn
quick pollen
verbal dome
#

Any method that returns a GameObject will fit where it wants a Func<GameObject>.

quick pollen
#

basically like a & pointer from c++

naive pawn
#

no not exactly

#

there's a different analogue to that

#

...or is it...

quick pollen
#

well I get that part

#

I just don't get what lambdas do for me

naive pawn
#

yeah ok it is like &var in c/c++

#

in fact c++ also has the same concept of lambda captures

#

just that here, it's always capture by reference, whereas in c++ you can decide if it's by reference or by value

quick pollen
#

yeahh

#

so I have that right

languid spire
quick pollen
naive pawn
quick pollen
#

I haven't even heard of delegates before

#

I mean right now I have some other issues with some mathematical calcs

naive pawn
#

lambdas are just a handy way to fulfill a delegate/action/func without needing a method
it's an "anonymous" method/function

languid spire
verbal dome
#
foreach(var thing in myList.Where(item => item.someBool))```
Used with Linq often too
#

This would let you iterate all things in the list that have someBool enabled

quick pollen
verbal dome
#

Vector3.Reflect the velocity with the collision normal

quick pollen
naive pawn
#

delegates/actions/funcs are about passing functions around as first-class members (objects)
sometimes you don't want to do something directly, but you want to tell something else to do something many times, or later, for example
like the filter osmal mentioned, or using actions for tasks (which you wouldn't do in unity, but just as an example)

languid spire
naive pawn
verbal dome
#

You can do that without lambdas, not the best exmaple in that sense

quick pollen
verbal dome
#

How are you detecting collisions? Physics/rigidbody? Manual casts?

naive pawn
#

a normal is a vector perpendicular to a plane
in this case, the plane of the collision would be tangent to the collision points
so the normal of the collision would be the "direction" of the collision

verbal dome
#

Contacts have normals

naive pawn
#

you don't, you let the smart people writing unity do that lol

#

see osmal's answer

verbal dome
#

You get it from Collision2D in OnCollisionEnter2D

quick pollen
#

oh, alright

#

its just weird that I'm using a 2D function

#

hold on, yeah, how would I go about that

verbal dome
#

Oh wait don't, if you use 3D physics use the 3D version

verbal dome
#

I didnt properly look at your video, looked 2D at a glance lol

quick pollen
#

ahh, thought so yeah

verbal dome
#

It's similiar in 3d tho

quick pollen
#

thing is, I'm using triggers

#

which have colliders, not collisions

verbal dome
#

Why?

quick pollen
#

because I want the projectiles to be triggers

verbal dome
#

That doesnt mean that the walls should be triggers does it

quick pollen
#

not through the walls

verbal dome
#

There's no way to get a contact from a trigger enter

#

Because no contact happened

quick pollen
#

so I need to write a script and place it on every single wall?

#

is there no better way to calculate it?

verbal dome
#

Or just use the bullet script?

naive pawn
quick pollen
verbal dome
#

That's a huge bandaid

naive pawn
#

should it hit the tank after it's fired?

quick pollen
#
            transform.rotation = Quaternion.Inverse(transform.rotation);```
also, if I do this mess, then the horizontal walls work, but not the vertical ones
verbal dome
#

Just disable collisions between the tank and the projectile

#

Physics.IgnoreCollision

quick pollen
naive pawn
#

what?

verbal dome
#

Or use the collision layer matrix

quick pollen
verbal dome
#

Sure, make one

naive pawn
#

have you considered, spawning it a bit in front of the barrel

#

or making the barrel not have collision

quick pollen
languid spire
quick pollen
#

I mean I switched to collisions already

#

now I just need to find the int I need to feed into the GetContact()

quick pollen
#

some projectiles can move slower, others faster

naive pawn
verbal dome
#

All of the suggestions in that stackoverflow thread have issues anyway

quick pollen
#

even with both methods, I get this

verbal dome
#

Who told you to put a rotation there

naive pawn
#

!collab 👇

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

languid spire
verbal dome
#

Yeah, though I would just use raycast/spherecast for the movement and collisions in the first place (if not collisions)

quick pollen
sand sonnet
naive pawn
verbal dome
naive pawn
quick pollen
naive pawn
#

!code

eternal falconBOT
quick pollen
naive pawn
#

but also... Gey key down?

sand sonnet
frail kettle
naive pawn
naive pawn
#

(also, that wasn't much of a suggestion, that just seemed like a complaint...)

sand sonnet
#

Im very sorry that you took it the wrong way

naive pawn
#

how would i take that as a suggestion, you aren't even suggesting anything there

#

anyways off topic

#

this server isn't a place for job posts

#

end of that

#

if you need help, see below
!ask

eternal falconBOT
quick pollen
#

this should work, yes?
if(gracePeriod > 0) Physics.IgnoreCollision(gameObject.GetComponent<Collider>(), other.collider, true);

#

ill probably get a ref to the collider in awake

verbal dome
#

What is other?

#

You cant ignore collisions after it already happened

quick pollen
#

private void OnCollisionEnter(Collision other) {

#

oh

#

idk how to do it then

naive pawn
#

set it when you fire the projectile, and then after a delay, set it to false

quick pollen
#

just the player's i guess?

naive pawn
#

yes

#

make the projectile and the player tank ignore each other

quick pollen
#

problem is, this wont work with enemy tanks

naive pawn
#

use a coroutine to do the delay bit, probably

quick pollen
#

cuz it wont ignore enemy tanks shooting this

naive pawn
quick pollen
naive pawn
#

ok?

#

how's that an issue

quick pollen
#

but if I set the collider to be just the player, it will ignore when the player shoots, but not when the enemy shoots

#

so the enemy tanks would instantly explode

naive pawn
#

make the projectile and the shooter ignore each other

#

like... that's not that hard

quick pollen
#

how do I check who shot it?

naive pawn
#

you don't

#

you just have a shooting script on each enemy, right?

#

you just get the current gameobject's collider

quick pollen
#

rn i only have the player, but yes

naive pawn
#

you don't need to check

#

the shooter is whoever this script is on

quick pollen
naive pawn
#

the "current" one that's shooting

verbal dome
#

If your projectiles are pooled then you want to re enable collision when returning it to the pool

quick pollen
#

also, the problem is that the projectiles go off on weird trajectories due to me not using triggers

verbal dome
quick pollen
#

yes

verbal dome
#

Isnt that the very issue we are talking about??

naive pawn
#

you didn't do the grace period correctly then?

quick pollen
#

i cant implement the grace period

#

thats what I'm talking about

naive pawn
quick pollen
#

i dont know which collider to ignore

naive pawn
#

the one on the shooter

#

the ability to shoot will be duplicated to each tank

quick pollen
naive pawn
#

so you'd just get the current gameobject's collider and have it ignore the instantiated bullet's collider

naive pawn
#

or just GetComponent<Collider>()

quick pollen
#

not the tank who shot him's collider

naive pawn
#

is shooting a function of the bullet?

quick pollen
#

bullets dont shoot?

naive pawn
#

exactly

verbal dome
#

What class does the shooting?

naive pawn
#

the shooting script would be on the tanks, right

quick pollen
naive pawn
#

yeah, so GetComponent<Collider>() would get the player's collider

quick pollen
#

i have an idea maybe

verbal dome
#

So when the tank shoots.. get its collider and ignore it with the bullet collider

quick pollen
#

okay it works, thanks!

naive pawn
#
public Collider bulletPrefab;
public float bulletGracePeriod;

Collider myCollider;

void Start() {
  myCollider = GetComponent<Collider>();
}

void OnShoot() {
  StartCoroutine(Shoot())
}

IEnumerator Shoot() {
  Collider bulletCollider = Instantiate(bulletPrefab);
  Physics.IgnoreCollision(myCollider, bulletCollider, true);
  yield return new WaitForSeconds(bulletGracePeriod);
  Physics.IgnoreCollision(myCollider, bulletCollider, false);
}
```does this make sense
this is not complete code, but you should be able to get the idea
quick pollen
#

this is the reflect thing

#

rb.velocity = Vector3.Reflect(transform.position, other.GetContact(0).normal);

verbal dome
#

You should not give it a position either

quick pollen
#

what should I give it then?

#

the velocity?

naive pawn
#

...dude

verbal dome
#

Are you being serious

quick pollen
#

I have no clue what its asking

#

The direction vector towards the plane.

#

thats the velocity

naive pawn
verbal dome
#

And this

#

Like come on

quick pollen
#

I know what normals are

#

but I didnt get what they had to do with it

naive pawn
#

do you know what reflection on a plane looks like

quick pollen
#

and yeah, I still dont get it

verbal dome
#

However now that you are using colliders and not triggers, you need to keep track of your previous velocity in a variable, updating it in fixedupdate

quick pollen
#

but what does a reflection on a cube looks like

verbal dome
#

Because in OnCollisionEnter the velocity has already changed

naive pawn
quick pollen
#
        rb.velocity = transform.forward * projectileSpeed * Time.deltaTime;
    }```
naive pawn
#

1 side plane of the prism

quick pollen
naive pawn
#

yeah but you don't reflect off the entire wall

verbal dome
naive pawn
#

you reflect off a side of the wall

verbal dome
#

I mean storing it in a Vector3

#

So you know the velocity that you had before the collision

quick pollen
#

yeah, but how do I change it then?

naive pawn
#

deltaTime doesn't make sense there

verbal dome
#

Oh yeah that's cursed

quick pollen
#

I checked like 2 vids and 3 forums

#

all of them used deltaTime

#

so I have no fucking clue

naive pawn
#

for Translate, maybe

verbal dome
#

Well, deltaTime is actually fixedDeltaTime in FixedUpdate

naive pawn
#

or for acceleration

quick pollen
verbal dome
#

Still doesn't make sense though

quick pollen
#

what else am I meant to type then?

naive pawn
#

Time.deltaTime is in seconds
velocity and projectileSpeed would already be in meters per second

so now you're assigning velocity to a value of meters, instead of meters per second

verbal dome
#

And adjust the speed accordingly

#

Then your projectileSpeed represents an actual speed in m/s

naive pawn
#

anyways since you're just using forwards as the travel direction, you could use that instead of the velocity

naive pawn
#

presumably you'd also want it to rotate instead of just changing velocity direction

verbal dome
quick pollen
#

I tried currentVelocity = Vector3.Reflect(currentVelocity, other.GetContact(0).normal);

verbal dome
#

If you mean using Vector3.Reflect(transform.forward, ...) in collisionenter

quick pollen
#

im still not understanding

quick pollen
# verbal dome ``rb.velocity = ``
    private void FixedUpdate() {
        rb.velocity = currentVelocity;
    }
    private void OnCollisionEnter(Collision other) {
        if(other.gameObject.CompareTag("Wall")){
            currentVelocity = Vector3.Reflect(currentVelocity, other.GetContact(0).normal);
            bounces--;
        }
    }
}```
verbal dome
#

Why did you change the other line, not the line i replied to?

#

Aah

quick pollen
#

didnt change anything yet

naive pawn
verbal dome
#

Collision has happened at that point, so pretty sure its before

#

87% sure

quick pollen
#

man

#

its just not working

#

its shooting in random directions

#

its not bouncing off properly

#

the bullets are spinning

verbal dome
#

Hint: It's the other way around

quick pollen
#

oh

#

but how else am I meant to do it?

verbal dome
#

You should honestly slow down a bit

#

Feels like you barely read most of our instructions

shadow briar
#

Hello everyone, im got a question about interfaces.

**Context: **
Making a very basic 2d shooter.
Had a issue where it only checked the top component if it has a Interface.

I saw on Unity learn it basically goes through each component, making lists with a loop, checks if said component implements the interface, and than go on from there.
Did some research, found a video by Infalliable Code, where they use Interfaces a bit differently from the Unity Learn, took the general concept and added it to my bullet script which is below:

private void OnTriggerEnter2D(UnityEngine.Collider2D collision)
{
    GameObject TempGO = collision.gameObject; // Get the game object so we can work with it.
    var dmgOBJ = TempGO.GetComponent<i_DMG>(); // Try and get the interface.
    if (dmgOBJ == null) return; // If no, return.
    dmgOBJ.OnHit(dmgOnHit); //Success, perform the I_DMG method.
    Destroy(gameObject); // destroy self
}```
And this works, even if i add in test scripts with no interfaces, so im happy with that.

**My main question is:** Is this generally a better way to use interfaces, less prone to errors and why does it work. 
i was under the impression that ``GetComponent`` simply got the top component, since i did a little test where i put a hitScript under a test script and it showed a error so that made me think why.
I just want to understand the why, to figure it out for future use.
quick pollen
#

currentVelocity = rb.velocity, but then how do I change rb.velocity

quick pollen
verbal dome
#

Hence the "slow down" part

#

Focus on 1 issue

quick pollen
#

but all of them corelate to each other

verbal dome
#

Focus on 1 issue

quick pollen
#

because they are all based on physics, and my physics is fucked

naive pawn
quick pollen
#

right now, if I try to shoot the projectile, it comes out in random directions, spinning like crazy

#

problem number 1

swift crag
#
if (!thingy.TryGetComponent(out IFoo foo))
  return;

foo.Bar();
verbal dome
swift crag
#

It makes for very readable code.

#

"if i try to get the component and that fails, return"

verbal dome
#

I find myself using the TryGet pattern a lot in my own code too

swift crag
#

I almost never use GetComponent

quick pollen
swift crag
#

Actually, let's do a codebase search...

#

rider isn't open, dammit

verbal dome
shadow briar
shadow briar
swift crag
#

I use it 23 times, and most of them are for getting HDAdditionalLightData, ha

swift crag
#

the vaguest request possible

naive pawn
swift crag
#

I was under the impression that it did

#

I don't think I've ever relied on that, mind you

naive pawn
#

GetComponent returns only the first matching component found on the GameObject, and components aren't checked in a defined order.

swift crag
#

Ah, figures

#

It probably has something to do with the order most of the time, but there is no guarantee

naive pawn
#

i'd guess insertion order probably

verbal dome
#

At that point you should use serialized references anyway :p

naive pawn
#

but like, no guarantees

verbal dome
#

Get the script component that has references to specific colliders

swift crag
#

Yeah, if you need to distinguish between multiple components that match the same type

#

There is no coherent way to do that without serialized references

swift crag
#

(other than getting all components that match the type and then picking one based on their members)

#

ah yes

quick pollen
#

i set the rb.velocity in enable

#

still doesnt work

swift crag
#
FindObjectsByType<Object>(FindObjectsSortMode.None)
quick pollen
#

shoots in random directions

#

I'm not even sure this works

verbal dome
#

Check if it's still colliding with the tank

#

Or its turret, if it has a collider

swift crag
verbal dome
#

You were supposed to do the ignore collision when you shoot the bullet

#

That was my idea, at least

#

You just need to enable the collision again after the grace period

naive pawn
shadow briar
#

So, just trying to make sure i understood interfaces, or getting access to interfaces from other scripts:

if (!TempGO.TryGetComponent(out i_DMG dmg)) { return; }
dmg.OnHit(dmgOnHit);

this in theory would always get access to the interface? as long as there was something that had a i_DMG interface on it in this context, it'd call it and send the value over for that script to do its "OnHit" stuff.

quick pollen
#

still completely random

#
            Debug.Log("shot");
            GameObject proj = ObjectPoolingProjectiles.Instance.Pools[0].Get();
            proj.GetComponent<BasicBullet>().shooter = gameObject.GetComponent<Collider>();
            Physics.IgnoreCollision(gameObject.GetComponent<Collider>(), proj.GetComponent<Collider>(), true);
            proj.transform.SetPositionAndRotation(tankCannon.transform.position, tankCannon.transform.rotation);
        }```
#

still random direction

verbal dome
quick pollen
#

wdym "other colliders"?

#

no, both of them have 1 collider

verbal dome
#

Log the thing you hit in OnCollisionEnter

quick pollen
#

this is why I didnt want to use OnCollisionEnter

shadow briar
# naive pawn yes

okay, cool.
I was concerned that i'd have to do the list loop stuff.

But thats cool, thank you and @swift crag for the input.

verbal dome
#

other.name

verbal dome
quick pollen
#

randomly hits tank

#

sometimes it does sometimes it doesnt

#

i just fired for like 5 seconds without moving, in the same direction

swift crag
#

sanity check by turning off the tank collider

quick pollen
#

it is STILL BAD

swift crag
#

quick pollen
#

i have 0 fucking clue

#

im using triggers rn

swift crag
#

that's good, actually

quick pollen
#

the thing that fucked it up is the whole currentVelocity thing

swift crag
#

you have gained information

quick pollen
#

it worked perfectly before that

swift crag
#

are you making it inherit velocity from the tank?

quick pollen
#
    private void FixedUpdate() {
        currentVelocity = rb.velocity;
    }```
stoic oracle
#

Spherecast isn't detecing a moving platform

quick pollen
#
    private void OnEnable() {
        lifetime = _lifetime;
        projectileSpeed = Mathf.Abs(projectileSpeed);
        bounces = _bounces;
        gracePeriod = _gracePeriod;
        currentVelocity = transform.forward * projectileSpeed;
        rb.velocity = transform.forward * projectileSpeed;
    }```
#

maybe the velocity gets set before the transform.forward is set to be the cannon's forward?

swift crag
#

oh, are you pooling projectiles here?

quick pollen
#

yes

#

...kinda

swift crag
#

can you share the updated code so I can see what you're currently running?

#

i'm pretty suspicious of using transform.forward

#

perhaps you're getting the direction the bullet had the last time it was fired

quick pollen
quick pollen
#

because I update it every single time I fire a projectile

#
    public void FireInput(InputAction.CallbackContext callbackContext)
    {
        if(callbackContext.performed){
            Debug.Log("shot");
            GameObject proj = ObjectPoolingProjectiles.Instance.Pools[0].Get();
            proj.GetComponent<BasicBullet>().shooter = gameObject.GetComponent<Collider>();
            proj.transform.SetPositionAndRotation(tankCannon.transform.position, tankCannon.transform.rotation);
        }
    }```
swift crag
#

Too late!

#

OnEnable already ran

quick pollen
#

I thought so

#

but what can I do then?

swift crag
#

You'll need to give it a Fire() method or something

#

set up the bullet and then call Fire

quick pollen
#

I cant set the rotation and position before I get it

swift crag
#

This is a common issue

#

Awake and OnEnable are too fast; Start is too slow

quick pollen
#

but if I call Get, it instantly instantiates and activates the object??

swift crag
#

It either instantiates a new copy or retrieves one from the pool

quick pollen
#

theres 0 frames between creation and activation

swift crag
#

OnEnable runs the instant that a Behaviour becomes enabled

quick pollen
swift crag
quick pollen
swift crag
quick pollen
#

thats why they start off random

quick pollen
#

which i dont want

swift crag
#

I didn't say to make the bullet inactive

quick pollen
#

but how can I set the position before it gets set active then?

swift crag
#

You don't

#

I just said that you need to give it another method that'll configure the rigidbody

#

Basically, move most of OnEnable into a Fire method that you explicitly call

quick pollen
#

but I can't configure the rigidbody before that

quick pollen
#

lemme guess, when I enable it

#

not solving anything

swift crag
#

after the bullet has been set up properly

quick pollen
#

wait, I think I get it

swift crag
#
var bullet = GiveMeBullet();
bullet.florps = 3;
bullet.explosion = "VERY BIG";
bullet.Fire();
verbal dome
#

I personally prefer a florps value of 9 but you do you

swift crag
#

OK boomer

quick pollen
#
    public void FireInput(InputAction.CallbackContext callbackContext)
    {
        if(callbackContext.performed){
            Debug.Log("shot");
            GameObject proj = ObjectPoolingProjectiles.Instance.Pools[0].Get();
            proj.GetComponent<BasicBullet>().shooter = gameObject.GetComponent<Collider>();
            proj.transform.SetPositionAndRotation(tankCannon.transform.position, tankCannon.transform.rotation);
            proj.GetComponent<BasicBullet>().Fire();
        }
    }``` in the tank
#
    public void Fire(){
        lifetime = _lifetime;
        projectileSpeed = Mathf.Abs(projectileSpeed);
        bounces = _bounces;
        gracePeriod = _gracePeriod;
        currentVelocity = transform.forward * projectileSpeed;
        rb.velocity = transform.forward * projectileSpeed;
    }```in the bullet
swift crag
#

Also, you shouldn't be pooling GameObject. You should be pooling the BasicBullet type!

#

If you want one pool per bullet type, consider having a method that looks like this

quick pollen
quick pollen
#

okay I fixed it

swift crag
#

Dictionary<Type, SomePool<Object>> pools;

public void Get<T>() {
  Type bulletType = typeof(T);
  return pools[bulletType].GetThing();
}
quick pollen
verbal dome
#

I already suggested a pool per type but they keep coming up with problems that don't exist

swift crag
#

well, it's not a pool, it's a memoizer

wintry quarry
quick pollen
#
    private void OnTriggerEnter(Collider other) {
        if(other.gameObject.CompareTag("Wall")){
            Debug.Log("wall");
            var collisionPoint = other.ClosestPoint(transform.position);
            var collisionNormal = transform.position - collisionPoint;
            currentVelocity = Vector3.Reflect(transform.forward, collisionNormal);
            bounces--;
        }
    }```this part still doesnt work
swift crag
#

which sounds gross

swift crag
#

it's about one step away from Javascrtipt

quick pollen
naive pawn
quick pollen
#

because like 6 other issues came up before that

verbal dome
#

I think I subconsciously avoid using readonly because it makes the var declarations so long

quick pollen
verbal dome
#

Why would they not pass thru?

#

You are only changing currentVelocity, not rb.velocity

swift crag
#

which you notably overwrite every physics step 😉

swift crag
#

a bit diabolical

quick pollen
#

i dont feel like getting into a whole different rabbit hole currently, im sorry

swift crag
#

You would do something a bit less audacious for your pools

quick pollen
#

i spent 5 hours setting up the pool just to go on and spend 10 hours setting up the memoizer?

swift crag
#

it is an illustrative example of how you can handle many kinds of things without writing a separate script for each type

quick pollen
#

rb.velocity = Vector3.Reflect(transform.forward, collisionNormal);, now it just slows down and passes through

naive pawn
quick pollen
naive pawn
#

right...

var collisionNormal = transform.position - collisionPoint;
this is not a normal

swift crag
#

isn't that bullet spinning wildly?

#

transform.forward has nothing to do with the velocity

quick pollen
#

tried using currentVelocity, did even less

naive pawn
#

one sec

#

so it is a normal, just offset a bit, for a flat surface should be fine...

swift crag
#

Ideally you should just go back to using non-trigger colliders

quick pollen
swift crag
#

such as...?

verbal dome
swift crag
#

remember that the bullets weren't hitting your tank's turret -- they were getting a totally bogus velocity

quick pollen
#

thats what caused the bogus velocity in the beginning

#

i kept getting logs from hitting the turret

naive pawn
#

after you did the grace period thing?

quick pollen
#

yes

swift crag
#

you need to ignore collisions immediately, not in Update.

quick pollen
#

    public void Fire(){
        lifetime = _lifetime;
        projectileSpeed = Mathf.Abs(projectileSpeed);
        bounces = _bounces;
        gracePeriod = _gracePeriod;
        currentVelocity = transform.forward * projectileSpeed;
        rb.velocity = transform.forward * projectileSpeed;
        Physics.IgnoreCollision(shooter, bulletCollider, true);
    }```
#

I do it in update too

#

increased the grace period, it seems to be better

swift crag
#

i think you need to take a break

quick pollen
#

i do, i have to go in 10 mins

#

I just really wanted to fix this cuz its so fucking stupid

#

I have 0 idea as to why it comes out spinning

#

it says theres no collision between anything

swift crag
#

You are pooling objects, so any state from the object's past life is perserved

#

This includes angular velocity.

quick pollen
#

but I literally set the velocity upon fire?

queen adder
#

I want to create a button Prefab, that's finds all the componates by itself. I was think about GetComponentinChilden, but i assume: It just uses the first TMP_Text every time. How to distinguish them by name?

swift crag
#

Angular velocity has nothing to do with linear velocity.

#

They are two separate values.

quick pollen
#

ill just set it to 0 then

#

that seems to fix it, thank you!

timber tide
#

they even renamed velocity to linear velocity to not confuse people this update lol

quick pollen
#

now its just the same issue with not reflecting

timber tide
#

ya not using 6?

quick pollen
#

no more

#

its way too buggy

obsidian plaza
#

hv i not seen yall talking in here for like 2 hours

#

r u fixing the same thing

swift crag
obsidian plaza
#

same

quick pollen
#

i have, with avatars mainly

#

theyre extremely buggy to edit

swift crag
#

that's always been busted

timber tide
swift crag
#

I've had headaches in 2022 editing humanoid avatar definitions for my VRChat avatars

quick pollen
obsidian plaza
#

oh wait @quick pollen u play realm cool

swift crag
quick pollen
#

also @swift crag last thing before I go, the projectile doesnt face the way its been reflected in, idk what to do for that

#

transform.rotation = Quaternion.LookRotation(rb.velocity); maybe?

#

ty all for the help!

#

man has this been a drag

quick pollen
queen adder
eternal falconBOT
queen adder
#
using TMPro;
using UnityEngine;
using UnityEngine.UI;


public abstract class Button : MonoBehaviour
{
    public ButtonDataBasic myData;
    private Button myButton;

    private Image mySprite;
    [SerializeField]private TMP_Text myHeadText;
    [SerializeField]private TMP_Text myDescription;
    [SerializeField]private TMP_Text myPriceTag;
    

    private void Awake() {
        myButton = GetComponent<Button>();
        

        if (myHeadText == null || myDescription == null || myPriceTag == null ) {
            Debug.LogError($"Button{name} misses componete");
        }
    }
    private void Start() {
        myButton.onClick.AddListener(UpdateButtonValue());
    }

    private void Update() {
        ActivedButton();
    }

    public void UpdateButtonValue() {

    }

    public void ActivedButton() {
        if(myData.Value > LogicManager.Instance.Score) {
            myButton.enabled = false;
        } else {
            myButton.enabled = true;
        }
    }
}
teal viper
runic lance
#

wait, your class is also called button

teal viper
#

Didn't notice that lol

runic lance
#

yeah that was subtle 😂

queen adder
runic lance
#

if you really want to call your class Button, you need to specify that the myButton variable is of the UnityEngine.UI.Button type

queen adder
gleaming turtle
#

Hi, I've got an issue where a game object, that is parented to another game object, won't move consistently with it's parent when it's moved, it'll move but very weirdly. the child game object has a rigidbody but is set to kinematic, the parent can have a rigidbody or not & the movement is still inconsistent. anyone know why this might be? i can provide a clip if necessary

gleaming turtle
teal viper
# gleaming turtle

Moving the object via transform and especially the gizmos is gonna be very unreliable. You should move it in code instead and using physics compatible ways(ideally).

gleaming turtle
#

okay let me show you a different example of when it's attached to another game object with a rigidbody

fervent abyss
#

im trying to make the torso rotate and i have a physics body (rigidbody) thats being moved by .Move, but my joint doesnt want to rotate. im trying to make so the torso looks down when the player is rotated, like gravity making objects fall towards it irl

teal viper
# gleaming turtle

Another possible cause is the scaling of the objects. Try with both of them scaled to 1

gleaming turtle
teal viper
gleaming turtle
#

I'll look into adjusting visual scales on import now

teal viper
cosmic dagger
gleaming turtle
teal viper
gleaming turtle
verbal dome
gleaming turtle
#

here's the code on my spear that controls flight & the piercing functionality (it's messy, this is my first proper project, i'm learning & using chatgpt so please no judgements lol)

verbal dome
#

Yeah I don't like the part in FixedUpdate

#

But first, try disabling interpolation and see if that helps 🤔

#

@gleaming turtle Actually, first try commenting out this part: rb.freezeRotation = true;

gleaming turtle
#

alright trying this now

bright arch
#

my coroutine only runs the first time, it is meant to run when i click (and the code before calling the start runs perfectly) is there anything i may be missing?

#

my code:

gleaming turtle
bright arch
teal viper
bright arch
#

i have it defined as a variable named cameraClick above

teal viper
bright arch
#

why does it work the first time then?

teal viper
#

I'd suggest checking the docs as well.

teal viper
#

How are you assigning it?

bright arch
#

in the start function it assigns it like this

gleaming turtle
verbal dome
teal viper
verbal dome
#

And does nothing

bright arch
verbal dome
#

In case you can't fix the current problems, that is

bright arch
teal viper
naive pawn
#

...can lambdas be used for coroutines?

verbal dome
#

You mean passed into one?

naive pawn
#

i guess, yeah

#

wait no

verbal dome
#

Yeah it's pretty common to pass in a callback to be called when it finishes, for example

teal viper
naive pawn
#
StartCoroutine((() => {
  yield return null;
})());
```as an iife, of sorts
verbal dome
#

Nah that doesn't work

naive pawn
#

hm, why not

#

oh, no proper target type for the lambda, right

heady mesa
#

hey guys

#

how do i make a script, ( for a vr game ) which a game objects disappears after a couple of seconds after touching it, but then resets all objects that dissapeared once 9 people are eleminated?

timber tide
#

good practice to assign coroutines in case you need to terminate them without having to destroy the GameObject

timber tide
gleaming turtle
gleaming turtle
#

I've set it so that once the spear pierces the game object, it starts ignoring collisions between them until it's been unpierced. however, it's also ignoring collisions with walls & the floor.

        parentCollider = collision.transform.GetComponent<Collider>();
        Physics.IgnoreCollision(GetComponent<Collider>(), parentCollider, true);```
this is the code i've used to disable collisions between the two
#

Anyone know why it would be ignoring collisions with other gameobjects, that don't have a rigidbody, as well now?

gleaming turtle
wintry quarry
# gleaming turtle

,well one issue is you're setting the position of this rigidbody directly via the Transform

#

transform.position += spearDirection * spearPierceOffset;

#

that can cause all kinds of havoc

gleaming turtle
#

yeah i've been told that is wrong however that is only done once the rigidbody is set to kinematic & that code works exactly as it's meant to, the issue is with collisions after it's pierced

crimson pike
#

there a way to get a better view style on the folder? like windows detail view

neat robin
#

what's the best channel to ask questions about proper component settings for camera/tile stuff?

neat robin
#

word ty ty

crimson pike
#

found it, one-column layout

verbal dome
#

You can ctrl+scroll for that btw

grand snow
#

i yern for the day that the grid view stops truncating file names too soon

crimson pike
#

would be nice if you could get a combination of the one-column view in that panel

#

with the left side folder browser

neat robin
swift crag
#

just overflow, dammit

#

do ANYTHING other than truncate the name like we're on a goddamn DOS computer

#

8.3 all the way

grand snow
swift crag
#

Substance Painter is really bad about this

#

I leave Unity on that "list view" perpetually

crimson pike
#

can i use the property drawer to make each element use different background contrasts so they are more visibly separate?

#

or is that writing a full ass editor?

#

like alternating two different shades of grey would be fine

verbal dome
#

You can probably do that with a property drawer and a ReorderableList

verbal dome
crimson pike
#

perfect! tx

autumn osprey
#

hey, so this is less of me having an issue with my current code, and more of me trying to understand an example provided. hope that's fine in this channel.

i'm currently trying to understand contact filters and how to use them. the main question i have currently is from this code snippet/example here: https://github.com/Unity-Technologies/PhysicsExamples2D/blob/d957391d0a2b70225ffdcaede90f40d679df5d1e/Assets/Scripts/SceneSpecific/Miscellaneous/SimpleGroundedController.cs#L17

he only references isGrounded twice, once during the declaration and once later in the code when checking if the character should be allowed to jump. How does isGrounded get updated past the initial declaration since it is never mentioned in OnCollisionEnter2D or any other update method? there is a high possibility i am not understanding what => does honestly.

(please let me know if i need to post the code in that link to a discord message, or if this isn't the right place for this question. thanks.)

GitHub

Examples of various Unity 2D Physics components and features. - Unity-Technologies/PhysicsExamples2D

verbal dome
#

If you use => it's an "expression-bodied property"

#

How does isGrounded get updated past the initial declaration
If you aren't familiar with properties, they don't actually store a value like fields do

#

This particular property is calling RigidbBody.IsTouching every time it is accessed

autumn osprey
#

i am not at all familiar with properties and this is extremely helpful actually

#

so the check actually runs m_Rigidbody.IsTouching(ContactFilter) because it is accessed, right?

naive pawn
#

properties are methods disguised as fields

autumn osprey
#

this makes complete sense now and i highly appreciate this. will need to look into how properties work more in depth in a bit, but i'm definitely on the right track now. thanks!

hot laurel
#

yeah properties are bad and misleading 🤐

edit:
alot of people expose empty properties (empty setter, empty getter method), in this case its misleading and usless/bad, it does nothing but it looks like method. Just use public field so nobody have to go to the implementation to check that it does nothing.

naive pawn
#

incredible reaction progression guys

brittle maple
#

!code

eternal falconBOT
brittle maple
#

I need to calculate in whic direction a character is moving, its using Transform (If im not wrong) to move, I tried using this code to calculate in which direction its moving, but that "totalPosition" isn't changing (its at 0, 0, 0) https://paste.ofcode.org/tLeh4r2aBFAApCLJf8un2x

wintry quarry
naive pawn
#

well firstPosition and secondPosition are gonna be the same value there

wintry quarry
#

also why did you make it so complicated with extra methods like that

brittle maple
naive pawn
#

you need a time step in between

wintry quarry
# brittle maple I guess I just do that xD, Is there any way to make this work? With Transforms?

What you want is probably this:

Vector3 previousPosition;

void Start() {
  previousPosition = transform.position;
}

void FixedUpdate() {
  Vector3 currentPosition = transform.position;

  // How much have we moved since the previous frame?
  Vector3 difference = currentPosition - previousPosition;

  // Velocity is distance / time
  Vector3 velocity = difference / Time.fixedDeltaTime;

  enemyAnim.SetFloat("moveX", velocity.x);
  enemyAnim.SetFloat("moveY", velocity.y);

  // Save our current position for next frame
  previousPosition = currentPosition;
}```
naive pawn
#

get the position, remember that, wait a bit for it to move, get the position again, find the difference

#

but yknow.. why not just have the thing controlling the movement, also report the direction?

#

also since this is animation stuff you might want to do this in Update? or is the target also moving in FixedUpdate for some reason

naive pawn
wintry quarry
#

yes - physics frames

brittle maple
#

Im finishing a gamejam in 2 hours, I gotta make this work fast, its using a script/plugin that I didn't fully study so I dont have time to see how it all works, thanks!!

naive pawn
wintry quarry
#

It's just easier to write frame than "physics update step" or whatever

naive pawn
#

i usually call them "physics ticks"

brittle maple
wintry quarry
#

but uh - what doesn't work about it?

brittle maple
#

In the inspector the totalPosition is still 0, 0, 0

wintry quarry
#

If you're in update then:

Vector3 velocity = difference / Time.fixedDeltaTime;```
This should be `Time.deltaTime` instead
naive pawn
#

is the target moving with Update or FixedUpdate?

wintry quarry
brittle maple
#

Sorry I changed it...

wintry quarry
#

you're subtracting two vectors that don't do anything

brittle maple
#

Thanks, im blind

wintry quarry
#

firstPosition and secondPosition are your old variables

#

You should use velocity.x and velocity.y

#

get rid of these:

    private Vector3 firstPosition;
    private Vector3 secondPosition;
    public Vector3 totalPosition;```
#

I would be inclined to put this all in LateUpdate as well assuming you are moving the object in Update

#

Or FixedUpdate if moving via physics

brittle maple
#

Im not sure, thanks, it works now!!!!

winged seal
#

how do i create a script?

frosty hound
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

winged seal
#

i asked bro

#

just tell me

#

aw

gleaming turtle
#

like that

winged seal
#

scriptable object

#

i have not used unity in 2 years

short hazel
#

Look at the screenshot

winged seal
#

i did

short hazel
#

Then you saw it too

gleaming turtle
#

if you need this much help with stuff like how to make a script, maybe you should in fact do the tutorials

short hazel
#

Indeed, the interface has changed a bit so some of the older knowledge isn't valid anymore

#

Official docs and tutorials are kept up to date though

cosmic quail
echo ruin
#

For me it still puts it at the top "Create C# Script"

cosmic quail
gleaming turtle
echo ruin
cosmic quail
echo ruin
#

I see

tacit crystal
#

how should i make a computer in my game?

wintry quarry
#

Because without that, nobody knows.

tacit crystal
#

well i want a computer that you can go to and turn it on and on there have some apps, but i'm wondering if i should do it by just turning on the UI when you turn it on or some other way

wintry quarry
tacit crystal
#

so i should just make UI in the right position of the monitor?

signal pollen
#

Hullo

#

I got a rudimentary thingy going. I want to ask for advice as to how to get the physics more... realistic? I currently just use a Vector3.foward * speed *timeDelta thingy when I probably want something more to do with the wheels and stuff?

sick jay
#

@trail heart its fun to see you in one of the courses im using

naive pawn
#

resize the game view to be vertical

#

or set a preset view size/dimension/ratio

#

you can also pull the game view out into a separate window

slender nymph
#

the shape of the scene view camera is entirely dependent on the resolution and aspect ratio set for the game view window

trail heart
signal pollen
#

Oh neat

obtuse pebble
#

Hi, I am making a game with Little Alchemy mechanics. I have worked out the art assets and combinations, and I now have to implement it. However, I am wondering what the best way to store the data would be.
In my limited C# usage, I would do an if loop to check every single combination, but I am sure there is a more effective way to do it. Any suggestions?

#

For those who don't know, the game revolves around combining two elements and making a new one. And there can be a lot of elements made, so a good and efficient way to store and track the combinations would be useful

grand snow
#

Could get costly if you add many possible combos.
A good option could be to look into having a unique id that be constructed from the components.

#

then using say a dictionary it would make lookups quick

obtuse pebble
#

a dictionary? I'll look into that. thanks!

grand snow
sick jay
#

The tutorial im following is using the new input system, but it looks like the editor has changed since then and I also want to try and add my own stuff. It wants me to add a using static Controls; in order to allow IPlayerActions to work properly, but VS wants me to use another one called UnityEngine.InputSystem.DefaultInputActions. it worked fine up until it wanted me to make an event that listens for movement, it doesnt like that its reading a vector2 value and wants it to be a bool. https://pastecode.io/s/swftznzb

slender nymph
#

your MoveEvent is an Action<bool> which means the event expects a bool parameter not a Vector2

sick jay
#

thank you

sick jay
#

Alright now im stuck. I know what I did was import the default controls which probably includes Onfire, OnLook, and OnMove, so its not actually using the input actions i made before. How do i set it to the correct input actions?

slender nymph
#

controls = new DefaultInputActions();
change this so it uses the type you created (assuming you're using the create c# class option for your input action map since this seems to be what the tutorial is doing)

sick jay
#

the Input Actions asset i made is called PlayerController, but it doesn't seem to show up anywhere in the script

slender nymph
#

look at the import settings for that and check what you made the c# class name for it

sick jay
#

I think I know what you're trying to ask me to do but I'm not sure how to get there

#

This is my first time using the input actions

slender nymph
#

click the asset, the inpsector will show the import settings. this is not an issue of not understanding input actions

sick jay
#

Oh the tutorial didn't mention having to generate a c# class for it

slender nymph
#

it should have if the tutorial is showing that you need to create an instance of the class. link the tutorial

sick jay
#

Its behind a paywall so I dont know if it will show up

#

I found it

trail heart
signal pollen
#

When I got it to work, and after tweaking a bunch of numbers, it was a real "Yippee!" moment

#

I am immensely grateful for the documentation but I wish I had like a "Oh man I need x thing to do y, but I don't know what the name of x is" thing

#

I guess the next best thing is to ask experts like you guys!

timber tide
#

zoom

pure drift
#

!code

eternal falconBOT
tough trench
#

anyone know how to fix this?

rich adder
#

If you use UVC then idk switch to git lol

tough trench
#

thanks

signal pollen
#

Just sharing for now. Question for later is how to make the item dropped off at the location pop up in a neat way. I am thinking, so as to avoid recursive stuff from occuring, I will make a copy of the crate pre-fab but with a different tag that isn't "collectibles" like the one found on the back of the truck

#

I am already thinking I will need to refactor the code, where the truck is storing information that it has 1 item already, so that it cannot pick up another

abstract copper
#
public class Bullet : MonoBehaviour
{
    [SerializeField] private BulletData BulletData;

    void Start()
    {
        Destroy(gameObject, 2f);
    }

    private void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.gameObject.CompareTag("Enemy"))
        {
            GameObject effect = Instantiate(BulletData.HitEffect, transform.position, Quaternion.identity);
            effect.transform.localScale = new Vector3(BulletData.EffectScale.x, BulletData.EffectScale.y, BulletData.EffectScale.z) * Random.Range(2f, 5f);

            collider.gameObject.TryGetComponent<Enemy>(out Enemy enemy);
            enemy.Damage(BulletData.Damage);

            Destroy(effect, 2f);
            Destroy(gameObject);
        }
    }
}

So I shot the enemy with a bullet that does 25 dmg twice and he died, but the enemy has a 100 health. What could be causing the duplicate damage?

wintry quarry
abstract copper
wintry quarry
#

and how much health the enemy has

#

and how much damage it's doing

#

and which collider you hit

abstract copper
#

okay

#

logged the health but didnt the other stuff il try

wintry quarry
#

logged the health where and when

#

and what was the result of that

abstract copper
#

only when it spawned

#

it was as expected

abstract copper
signal pollen
wintry quarry
#

Not a code question

#

But you need to fix your UV mapping and/or texture scaling

#

or consider using a Triplanar shader

#

Shader Graph has a Triplanar node

abstract copper
#

so it hit the collider extra 2 times

wintry quarry
abstract copper
#

it has 2, but only 1 has trigger enabled

wintry quarry
abstract copper
#

yes

wintry quarry
#

it will run OnTriggerENter2D for each other collider it hits

#

whether thye're triggers or not

#

that's why I suggested logging which collider you're hitting

abstract copper
#

Didnt know that

#

How should i do it? i still wanna let the enemy collide with stuff

#

It works fine when i remove the other collider

stuck field
wintry quarry
abstract copper
#

fixed it, i just made another gameobject with the collison collider without a layer and used layers instead of tags

#

thanks

crisp olive
#

anyone know how to make hexadecimal strings?

#

have this simple idea that once you break it down its not so simple, at least for a beginner

wintry quarry
#

An int?
A byte array?

crisp olive
#

my basic idea is i want to manipulate an objects color with hex color codes(bullets) and if the hex matches then enemies hex color it destroys it

#

instead of having 3 diffrent spawners and deleting them after cycling i wanna use one object and cycle hex codes if possible

crisp olive
#

Dudeeee thank you! this is perfect

#

making my first game super hyped!

whole willow
#

I'm starting to feel stupid... Why does the object with the Rigidbody attached not send the debug message on entering the other BoxCollider

slender nymph
rich adder
whole willow
rich adder
#

& not in update either

whole willow
#

so what should I do instead?

rich adder
#

use fixedupdate

whole willow
#

but that messes with the predictable logic of the object... Now it's going all over the place

#

I don't really have the time for this either

rich adder
#

show what you have

#

if you want OnCollision to work properly you shoud move it with the appropriate physics methods, you are using a phyiscs function

whole willow
#
using System.Collections.Generic;
using UnityEngine;

public class Cycle : MonoBehaviour
{
    [SerializeField] private SteeringWheel steeringWheel;
    [SerializeField] private float forwardSpeed = 10f;
    [SerializeField] private float turnSpeed = 5f;
    [SerializeField] private float deadZone = 5f;

    private Rigidbody rb;
    public bool DeadZoneActive { get; private set; }

    private void Awake()
    {
        rb = GetComponent<Rigidbody>();
        if (rb == null)
        {
            Debug.LogError("Rigidbody component is missing on this object.");
        }
        DeadZoneActive = true;
    }

    private void FixedUpdate()
    {
        if (rb == null)
            return;

        Vector3 forwardForce = transform.right * forwardSpeed;
        rb.AddForce(forwardForce, ForceMode.Force);

        // Rotate the motorcycle based on the steering angle
        if (steeringWheel != null)
        {
            float steeringAngle = steeringWheel.SteeringAngle;

            if (Mathf.Abs(steeringAngle) > deadZone)
            {
                DeadZoneActive = false;
                Quaternion targetRotation = Quaternion.Euler(0, -steeringAngle * turnSpeed, 0);
                Quaternion newRotation = Quaternion.Lerp(rb.rotation, rb.rotation * targetRotation, Time.fixedDeltaTime);
                rb.MoveRotation(newRotation);
            }
            else
            {
                DeadZoneActive = true;
            }
        }
    }

    private void OnCollisionStay(Collision collision)
    {
        Debug.Log("ouch");
    }
}
``` It no longer properly rotates and while the Debug message wasn't triggered, it just went flying
rich adder
#

it goes flying probably because you have Accumulating speed with AddForce

#

if you want behavior similar to translate you can use .velocity or switch the ForceMode without mass / acceleration but you still need a velocity "speed limit" aka clamp

whole willow
#

I'm such a freaking idiot...

I muted the console.
Don't debug at 4 am, kids.

@rich adder thank you so much tho!

ember talon
#

Hi, is anybody here has experience working with Unity Timeline? I'm working on a feature by extending Unity's Timeline and found an issue on the scrubber;
when I jump the scrubber to previous time, it won't evaluate the PlayableAssets within the range of the scrubber's traversal. Is there a workaround for this?

ember talon
#

Alright, I'll move it there. Thanks for reminding

crimson pike
#

First order of business in debugging any problem that was working just a moment ago is reiterating over every setting you can think of.

Like this morning I went to demo this feature I made Th e night before that suddenly didn’t work, simple letterbox effect right? Well the parameters all looked fine and it took me an hour to realize the alpha value was just 0 so it wasn’t showing up

wintry quarry
#

Get a reference like any other component

slender nymph
#

note that creating an instance of your PlayerInput class generated by the input action asset is not creating an instance of that PlayerInput component, but rather a specific class meant to handle the input directly. having more than one instance of that is also perfectly fine as you can enable/disable specific action maps on it if you want. but also you can just pass the reference to the PlayerInput object

wintry quarry
#

yes that's wrong

slender nymph
#

nah, the youtube tutorial you followed just named the generated c# class the same as the existing component which made that more confusing

wintry quarry
#

wll good. chance you ccidetally named your actions asset that and you're thinking of the generated class

#

which is stupid

#

but common

#

yeah you're confusing the actual PlayerInput component with your generated class

#

no

#

that's your asset

#

name it something else

#

so you get less confused

#

because you are confused right now

#

the fact you are usng the compoonent and the generated class is wrong

#

you need to pick one or the other

nimble apex
#

lol i just found out

InputField.textcomponent.text```
 and 
```cs
InputField.text```might be different
#

somehow they will add a zero whitespace there

north kiln
#

Yes, the child TextMeshProUGUI uses a zero-width space for layout purposes, and should not be referenced.

wintry quarry
#

Again it's because you named your asset "PlayerInput"

#

so you have a generated C# class with that name too

#

which is causing you confusion

#

you should rename the asset, and delete the old generated C# class if it exists

#

which it clearly still does

#

The error is clearly saying you have a script called PlayerInput that doesn't derive from MonoBehaviour

#

Go to this code

#

right click the word "PlayerInput"

#

and "jump to definition" or whatever

#

The error is clear that it still exists

#

yes right click this word

#

the capital one

#

go to that definition

#

that would be a totally different error

#

You deleted it but did you uncheck the checkbox on the asset? Because it will re-generate it if you didn't

#

I still recommend renaming the asset as well to avoid further confusion

#

Yeah because that code is not valid

#

You are trying to use the PlayerInput component now as if it were the generated class

#

It isn't. It's not going to have those properties with the names of your action map etc.

#

Huh?

#

Why would you need to? You are doing something weird if you're asking that question

#

yeah you can't do this

#

Invoke unity events is when you set up listeners in the inspector for the component

#

you don't set up listeners in your code.

#

You set them up like this

#

absolutely no

#

You still get a CallbackContext parameter with Unity Events

#

you just check in the code

#

e.g.

if (context.performed) // whatever```
#

That's what I just said

#

WHy?

#

Why do you need it?

#

What are you talking about

#

what isn't working

#

you don't need this code at all

wintry quarry
#

but agian

#

if you're getting that error it means you still have another class called PlayerInput you defined somewhere

#

most likely the generated one

#

unless you mean these

#

Yeah that code has to be deleted

#

like I said it's not valid anymore

wintry quarry
#

Then you shouldn't be using the PlayerInput component

#

you said you prefered the component before

#

It's possible to still have the component but it's pointless

#

you don't need it but it's the most convenient way.

#

You should really rename it

#

because that's very confusing

#

that will create different instances

#

It's a C# object like any other. You can share a reference to it as you need to.

I recommend making a single component that manages a single instance of it

#

and share that amongst all the scripts that use it

#

that way if you do:

  • runtime rebinding
  • runtime enabling/disabling of action maps

It all works globally

#

sure

#

Make a component like I described, and make it a singleton

#

Basic example:

public class InputHolder : MonoBehaviour {
  public static InputHolder Instance { get; private set; }

  public MyInputAsset Input { get; private set; }

  void Awake() {
    Instance = this;
    Input = new();
  }
}```
#

Not sure what you mean by "include it as a Component"

#

but you can access this via the Instance property from anywhere

#

Not in Awake

#

In Start or Update

charred spoke
#

Yes

burnt vapor
#

If you worry about availability then you should just make a general provider that provides your singletons rather than have them create themselves. Then it would not matter who grabs it first.

#

There are cases where an instance requires a singletons in its awake state for initialization, so then you would still have an issue

copper crest
#

Can someone tell me how do i make a button that triggers another animation on the UI

rich adder
copper crest
#

Oh i got it

dapper yarrow
#

Anyone know how to attach audio souce to a prefab and player properly? I am able to attach it but whenever the script tried to play it, error "Can not play a disabled audio source" would occur...

rich adder
dapper yarrow
#

but I am not sure why it is disabled. I am using another script to spawn coin (the prefab). I attached a script to the coin to trigger when player collide with it, which play the sfx, and disable the object

#
public class SFXManager : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField] private AudioSource coinSFX;
    void Start()
    {
        if (coinSFX == null)
        {
            coinSFX = GetComponent<AudioSource>();
        }
    }
    void OnTriggerEnter (Collider other) {
        coinSFX.Play();
        this.gameObject.SetActive(false);
    }
}
#

but even if I remove the setactive command, the same error would still occur

rich adder
dapper yarrow
rich adder
dapper yarrow
#

okie! Just a sec. Thanks for helping btw!

rich adder
#

Debug.Log($"{name} is active {gameObject.activeSelf} and coinSFX state : { coinSFX.enabled} to play")

dapper yarrow
#

weird🤔

rich adder
# dapper yarrow

are you sure this object is not getting destroyed or disabled in the same frame?

dapper yarrow
#

let me try removing the disable command

rich adder
#

you might be better off playing the sound from elsewhere if you don't need spatial 3d sound

dapper yarrow
rich adder
dapper yarrow
#

Thanks!! Much appreciate for the beginner article!

tough plinth
#

Hello everyone!
So I'm trying to make a code that changes Camera view (from 3rd to 1st person view) and I'm a bit confused with my script:

https://hastebin.skyra.pw/zagihoyoqa.csharp

It works well until I add another If statement. Logically it should work but for some reason it's not.

Any thoughts?

visual linden
#

Alternatively, you can use Else in place of the second block

#

To ensure only one of them gets executed

tough plinth
#

Oh, never thought the problem could be in return;
Previous language didn't require that D:

#

Oh, it works now, thanks!

visual linden
#

Returning just ensures that the code doesn't continue. In your case you only want to evaluate one of the two if blocks