#💻┃code-beginner
1 messages · Page 573 of 1
that is the lambda capture of the variable i. Very important
But it can have a 3D rotation/normal
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?
ok?
but its not even used anywhere?
I'm just being a smartass because you were being one
yes, it is it is passed to the CreatePooledItem method
can we stop fighting? im literally here to ask a question
please dont deviate
oh you edited it, okay
Sure it is, as an argument to the function on the following line.
it wasn't like that before
why can't you just pass i directly?
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
true
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
ohh
Because the value will change and persist
there's 2 widths and heights here, can you clarify whether you mean the total height/width of the board or the height/width of any given cell?
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
I mean. I dont have the total width/height or rows or even columns. I just know that i wanna fit 120 blocks (or any number of blocks) on a plane of some size. Now I am confused how to determine the width and height? BEcause I am thinking that i would need the plane's width and height right?
you would, yes
and how would i get that
you could define it yourself
looks fine
just define that the base plane is some size and then base your other calculations on that assumption
i am sorry, but can you explain it a little more
it says its out of range
how do i assume it
wouldn't you need to have the int x outside the lambda
no
Yes
you just make a decision
are projectiles and pools the same length
oh
well I only create projectiles.Count amount of pools
and projectiles.Count right now is 1
so Pools.Length should also be 1
ill try to log it
wait Pools is a List is it not
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
no, needs to be an array of length [projectiles.Count]
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
no it wont, if you do not have the x you have no lambda capture so then it will have the wrong i value
what is the "right" i value? the last value or the value for each iteration?
value per iteration of course
So initialize it elsewhere or use a const for the projectile pool count
so having the x = i inside the lambda would just get the last value of i, same as if you just used i in the lambda directly
fair
because it's also used in the lambda
well, I'm still having issues with understanding lambdas
public IObjectPool<GameObject>[] Pools;
```private void Awake() {
Pools = new IObjectPool<GameObject>[projectiles.Count];
...
now
GameObject newPooledObject = Instantiate(projectiles[i]);
is out of range
i did it yeah
edited
Because of what Chris said
is projectiles.Count 1 here?
yes
yeah the capture is the issue
so I should make the x non-local?
You just move the int x = i before the lambda
yeah now it works
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;
}
man, this is getting me kinda brainfucked ngl
lambdas are just functions as objects
I just need to understand what that means for me
I know what functions and objects are
well, objects more or less
you are missing the int x = i
o right true
inside the for
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
also the fact that I didn't need no Func or Action
this is captured because CreatePooledItem is a member of this (your class)
ObjectPool says it does that, you just have to supply a matching value
yeah no I understand that part
its passed by reference, not by value
Any method that returns a GameObject will fit where it wants a Func<GameObject>.
basically like a & pointer from c++
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
in this case they allow you to pass a parameter into a method which you otherwise would not be able to do
yeah, that part I understand, but what else are they generally used for?
lambdas specifically or delegates in general?
I think both
I haven't even heard of delegates before
I mean right now I have some other issues with some mathematical calcs
lambdas are just a handy way to fulfill a delegate/action/func without needing a method
it's an "anonymous" method/function
this is the most common use
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
need to find some formula to bounce projectiles off of walls
right now I just do transform.rotation = Quaternion.Inverse(transform.rotation);
Vector3.Reflect the velocity with the collision normal
what if you just checked if item.someBool is true, and did something if it was?
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)
but that can (and should) be done without using Linq and lambdas. In the current use case there is no other option
you could, that would have the same behavior basically
You can do that without lambdas, not the best exmaple in that sense
I see
wdym collision normal? whats the normal of the collision? its rotation?
How are you detecting collisions? Physics/rigidbody? Manual casts?
physics
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
Collision2D has contacts and GetContact()
Contacts have normals
how do I calculate that?
You get it from Collision2D in OnCollisionEnter2D
oh, alright
its just weird that I'm using a 2D function
hold on, yeah, how would I go about that
Oh wait don't, if you use 3D physics use the 3D version
I didnt properly look at your video, looked 2D at a glance lol
ahh, thought so yeah
It's similiar in 3d tho
Why?
because I want the projectiles to be triggers
That doesnt mean that the walls should be triggers does it
the walls arent, but I'm detecting collision through the bullet
not through the walls
so I need to write a script and place it on every single wall?
is there no better way to calculate it?
Or just use the bullet script?
why exactly?
so it doesnt push the tank around whenever it gets fired from the barrel, as an example
That's a huge bandaid
should it hit the tank after it's fired?
transform.rotation = Quaternion.Inverse(transform.rotation);```
also, if I do this mess, then the horizontal walls work, but not the vertical ones
well thatd mean that the tank gets stuck
what?
Or use the collision layer matrix
but I want you to be able to be killed by your own projectiles, so I have to make a grace period
Sure, make one
have you considered, spawning it a bit in front of the barrel
or making the barrel not have collision
wouldnt be good because then, if you were moving in the direction you were firing, youd still die
I mean I switched to collisions already
now I just need to find the int I need to feed into the GetContact()
how fast are your tanks moving
bout the same speed as the projectiles
some projectiles can move slower, others faster
0, probably
uh if your projectile moves slower than your tank and you go in the same direction you're shooting i think that would make sense for it to die
All of the suggestions in that stackoverflow thread have issues anyway
even with both methods, I get this
Who told you to put a rotation there
!collab 👇
: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
true, but they are a starting point rather than just saying 'can't be done'
Yeah, though I would just use raycast/spherecast for the movement and collisions in the first place (if not collisions)
what am I meant to use then?
but nobody will answer me on there and i wont get notified if someone does answer me
Vector3.Reflect the velocity with the collision normal
You really still cant use the documentation?
...ok? doesn't mean job posts are accepted here
irrelevant
oh, im stupid
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
its just that there it changed the position
but also... Gey key down?
im just suggested that you add something like a job board
lol nvm just saw the word get became gey for no reason XD
no thanks
you didn't suggest that.. you just posted a job offer
was suggesting that here
we have a suggestion channel
https://discord.com/channels/489222168727519232/1265239843328229416
(also, that wasn't much of a suggestion, that just seemed like a complaint...)
Im very sorry that you took it the wrong way
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
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
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
set it when you fire the projectile, and then after a delay, set it to false
yes but ignore which collider
just the player's i guess?
problem is, this wont work with enemy tanks
use a coroutine to do the delay bit, probably
cuz it wont ignore enemy tanks shooting this
why wouldn't it
I want players and bots using the same projectile
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
how do I check who shot it?
you don't
you just have a shooting script on each enemy, right?
you just get the current gameobject's collider
rn i only have the player, but yes
which "current gameobject"?
the "current" one that's shooting
If your projectiles are pooled then you want to re enable collision when returning it to the pool
also, the problem is that the projectiles go off on weird trajectories due to me not using triggers
Because they are hitting the shooter right?
yes
Isnt that the very issue we are talking about??
you didn't do the grace period correctly then?
thats my problem!!
i cant implement the grace period
thats what I'm talking about
SAM tanks 😭
i dont know which collider to ignore
yes, how do I tell the bullet who shot him?
so you'd just get the current gameobject's collider and have it ignore the instantiated bullet's collider
gameObject.GetComponent<Collider>()
or just GetComponent<Collider>()
thats the bullet's collider
not the tank who shot him's collider
is shooting a function of the bullet?
exactly
What class does the shooting?
the shooting script would be on the tanks, right
a class on the player currently
yes
yeah, so GetComponent<Collider>() would get the player's collider
i have an idea maybe
So when the tank shoots.. get its collider and ignore it with the bullet collider
okay it works, thanks!
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
except for this
this is the reflect thing
rb.velocity = Vector3.Reflect(transform.position, other.GetContact(0).normal);
You should not give it a position either
...dude
Are you being serious
I have no clue what its asking
The direction vector towards the plane.
thats the velocity
you responded to this
do you know what reflection on a plane looks like
and yeah, I still dont get it
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
I know
but what does a reflection on a cube looks like
Because in OnCollisionEnter the velocity has already changed
I am
you don't do that, you do reflection on planes
rb.velocity = transform.forward * projectileSpeed * Time.deltaTime;
}```
1 side plane of the prism
well the wall is a cube
yeah but you don't reflect off the entire wall
That's not "keeping track" of the velocity, that's just assigning to the velocity
you reflect off a side of the wall
I mean storing it in a Vector3
So you know the velocity that you had before the collision
yeah, but how do I change it then?
uhh this is not how velocity works
deltaTime doesn't make sense there
Oh yeah that's cursed
I checked like 2 vids and 3 forums
all of them used deltaTime
so I have no fucking clue
for Translate, maybe
Well, deltaTime is actually fixedDeltaTime in FixedUpdate
or for acceleration
I know that
Still doesn't make sense though
what else am I meant to type then?
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
Just remove the * Time.deltaTime
And adjust the speed accordingly
Then your projectileSpeed represents an actual speed in m/s
anyways since you're just using forwards as the travel direction, you could use that instead of the velocity
presumably you'd also want it to rotate instead of just changing velocity direction
yeah
The collision can change the forward vector though
I tried currentVelocity = Vector3.Reflect(currentVelocity, other.GetContact(0).normal);
If you mean using Vector3.Reflect(transform.forward, ...) in collisionenter
im still not understanding
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--;
}
}
}```
didnt change anything yet
would the change happen before or after OnCollisionEnter though
man
its just not working
its shooting in random directions
its not bouncing off properly
the bullets are spinning
rb.velocity = currentVelocity;```
Told you to store the velocity in a variable. Does this do that?
Hint: It's the other way around
yes, cs private void OnEnable() { lifetime = _lifetime; projectileSpeed = Mathf.Abs(projectileSpeed); bounces = _bounces; gracePeriod = _gracePeriod; currentVelocity = transform.forward * projectileSpeed; }
oh
but how else am I meant to do it?
You should honestly slow down a bit
Feels like you barely read most of our instructions
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.
currentVelocity = rb.velocity, but then how do I change rb.velocity
I am trying to, but theres 3 issues being covered at the same time
but all of them corelate to each other
Focus on 1 issue
because they are all based on physics, and my physics is fucked
GetComponent<T> gets a component that matches T
right now, if I try to shoot the projectile, it comes out in random directions, spinning like crazy
problem number 1
btw, check out TryGetComponent if you're going to be doing this a lot
if (!thingy.TryGetComponent(out IFoo foo))
return;
foo.Bar();
Put the whole script in a paste site and don't change it yet
It makes for very readable code.
"if i try to get the component and that fails, return"
I find myself using the TryGet pattern a lot in my own code too
I almost never use GetComponent
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
So first of all, the FixedUpdate part should be currentVelocity = rb.velocity;
Before that though, set the velocity to whatever you need it to be
So, it isnt just the top component? okay that makes more sense.
Ah, thank you, i'll try and use it more in future notes
I use it 23 times, and most of them are for getting HDAdditionalLightData, ha
It would do that if you did something like GetComponent<Component>!
the vaguest request possible
well no since GetComponent doesn't use the order in the inspector
I was under the impression that it did
I don't think I've ever relied on that, mind you
GetComponentreturns only the first matching component found on the GameObject, and components aren't checked in a defined order.
Ah, figures
It probably has something to do with the order most of the time, but there is no guarantee
i'd guess insertion order probably
At that point you should use serialized references anyway :p
but like, no guarantees
Get the script component that has references to specific colliders
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
okay, did that
(other than getting all components that match the type and then picking one based on their members)
ah yes
FindObjectsByType<Object>(FindObjectsSortMode.None)
It may be too late by that point
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
😔
if you were wrong this wouldve been so much easier lmao
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.
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
yes
Is this script on the tank object? Or is it on the turret? Does the turret or the tank have other colliders?
tank
wdym "other colliders"?
no, both of them have 1 collider
Log the thing you hit in OnCollisionEnter
this is why I didnt want to use OnCollisionEnter
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.
other.name
Okay go back to using triggers then
randomly hits tank
sometimes it does sometimes it doesnt
i just fired for like 5 seconds without moving, in the same direction
sanity check by turning off the tank collider
it is STILL BAD
✨
that's good, actually
the thing that fucked it up is the whole currentVelocity thing
you have gained information
it worked perfectly before that
are you making it inherit velocity from the tank?
private void FixedUpdate() {
currentVelocity = rb.velocity;
}```
no
Spherecast isn't detecing a moving platform
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?
oh, are you pooling projectiles here?
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
which should be impossible
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);
}
}```
You'll need to give it a Fire() method or something
set up the bullet and then call Fire
I cant set the rotation and position before I get it
but if I call Get, it instantly instantiates and activates the object??
It either instantiates a new copy or retrieves one from the pool
theres 0 frames between creation and activation
OnEnable runs the instant that a Behaviour becomes enabled
well rn it only instantiates whenever I start firing, it doesnt pre-bake
Right, but I presume that bullets go back in the pool after they expire
what can I do then? i cant do this
yes
...why?
thats why they start off random
if I set it inactive, it gets set back into the pool
which i dont want
I didn't say to make the bullet inactive
but how can I set the position before it gets set active then?
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
but I can't configure the rigidbody before that
and when do I call that?
lemme guess, when I enable it
not solving anything
after the bullet has been set up properly
wait, I think I get it
var bullet = GiveMeBullet();
bullet.florps = 3;
bullet.explosion = "VERY BIG";
bullet.Fire();
I personally prefer a florps value of 9 but you do you
OK boomer
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
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
no, I will have different projectiles, not all of them will have basicbullet
One pool per type
okay I fixed it
Dictionary<Type, SomePool<Object>> pools;
public void Get<T>() {
Type bulletType = typeof(T);
return pools[bulletType].GetThing();
}
id need to write a new script for every new projectile type i add
No you wouldn't
I already suggested a pool per type but they keep coming up with problems that don't exist
I don't think you've thought through how it would work otherwise. What happens when the pooled object you pull out doesn't have the component type you want?
You need one pool per type and no it doesn't involve writing a new pool for each type just use a Dictionary
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
I presume that Pools[0] means "the basicbullet pool"
which sounds gross
private static readonly Dictionary<object, IDictionary> Maps = new();
This is one hell of a type
it's about one step away from Javascrtipt
i havent gotten to that part yet
1 step away from ts maybe..
because like 6 other issues came up before that
I think I subconsciously avoid using readonly because it makes the var declarations so long
projectiles just pass through
Why would they not pass thru?
You are only changing currentVelocity, not rb.velocity
which you notably overwrite every physics step 😉
oh right
This can memoize ANYTHING, keyed on the constructor function
a bit diabolical
i dont feel like getting into a whole different rabbit hole currently, im sorry
You would do something a bit less audacious for your pools
Just this, really
i spent 5 hours setting up the pool just to go on and spend 10 hours setting up the memoizer?
it is an illustrative example of how you can handle many kinds of things without writing a separate script for each type
rb.velocity = Vector3.Reflect(transform.forward, collisionNormal);, now it just slows down and passes through
you're setting the velocity to a direction
still doesnt change the fact that it keeps moving in the same direction
right...
var collisionNormal = transform.position - collisionPoint;
this is not a normal
isn't that bullet spinning wildly?
transform.forward has nothing to do with the velocity
tried using currentVelocity, did even less
great
Ideally you should just go back to using non-trigger colliders
which causes even more problems than it solves
such as...?
The whole point was to use solid colliders and reflect currentvelocity with the normal
remember that the bullets weren't hitting your tank's turret -- they were getting a totally bogus velocity
nono, they were
thats what caused the bogus velocity in the beginning
i kept getting logs from hitting the turret
after you did the grace period thing?
you need to ignore collisions immediately, not in Update.
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
didnt I JUST fix that fucking issue with the rotations not being okay??
i think you need to take a break
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
You are pooling objects, so any state from the object's past life is perserved
This includes angular velocity.
but I literally set the velocity upon fire?
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?
Angular velocity has nothing to do with linear velocity.
They are two separate values.
they even renamed velocity to linear velocity to not confuse people this update lol
now its just the same issue with not reflecting
in code its still velocity
ya not using 6?
I have not observed any serious problems in 6
same
that's always been busted
Any reason you don't just serialize the buttons text explicitly. Otherwise, you'd probably want to use GetComponentsinChildren which would return an array of them
I've had headaches in 2022 editing humanoid avatar definitions for my VRChat avatars
not in 2021
oh wait @quick pollen u play realm cool
yupp
mostly involving the muscle settings being very fiddly
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?
finally it works
ty all for the help!
man has this been a drag
they only got fucked over here because of colliding with each other, which is fine
I'm i dumb? Does the Button have no onClick ? I already google it, is onClick stiil up to date? https://docs.unity3d.com/2018.3/Documentation/ScriptReference/UI.Button-onClick.html (using TMPro;
using UnityEngine;
using UnityEngine.UI;)
Share the whole script. !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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;
}
}
}
Is that only in the IDE? Does the code actually compile? Or do you get an error in the console?
wait, your class is also called button
Didn't notice that lol
yeah that was subtle 😂
Renamed it, now the error is gone Thanks!
if you really want to call your class Button, you need to specify that the myButton variable is of the UnityEngine.UI.Button type
Ah thats possiable? Thanks i will try 🙂
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
Providing a vieo would help
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).
okay let me show you a different example of when it's attached to another game object with a rigidbody
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
Another possible cause is the scaling of the objects. Try with both of them scaled to 1
the spear is scaled to 12, 12, 12 as it is tiny otherwise, and all objects it's a child of are uniformly scaled as well
i'm gonna have to send a google drive link for next clip as it's too big for discord :(
- You should adjust your visuals scale in the model import settings.
- You can upload it to https://streamable.com/ or a similar service and paste a link. It should be viewable in the discord then.
ug
I'll look into adjusting visual scales on import now
Upload from your PC. Not google drive.
ready to send 5$ for this
That's not the website they linked . . .
that means i have to create an account annoyingly, alright give me a min
I don't think you need. Just click here
You were previously moving the spear with transform. What does your current code look like?
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)
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;
alright trying this now
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:
tried this & no joy, same issue, i'll try the interpolation disable now
this is the debug log after clicking twice
your coroutine is named CameraClick, not cameraClick
i have it defined as a variable named cameraClick above
That's not how it works. You can assign the return value of StartCoroutine to that variable, but not pass it as a parameter.
why does it work the first time then?
I'd suggest checking the docs as well.
Good question.
How are you assigning it?
in the start function it assigns it like this
okay this worked, the spear now stays in place on the gameobject it's thrown at, getting some weird issues if i throw it at a box with a rigidbody where the spear wants to keep moving around after but i can have a crack at that
My guess is, the first time it runs and completes. The second time you start the same coroutine, it has already completed
Ah, well that might just work. One time.
But anyways, that's not the correct way.
And does nothing
cheers @verbal dome :)
ahh then how does one reuse the same coroutine within code?
No problem, btw FixedJoint also exists if you want to try an alternative for attaching a rigidbody to another, instead of parenting
In case you can't fix the current problems, that is
ill change it to this i guess but it tells me its invoked using a string literal and i suppose they want me to change it for some reason
There's another proper way. Read the whole docs page
...can lambdas be used for coroutines?
You mean passed into one?
Yeah it's pretty common to pass in a callback to be called when it finishes, for example
It's not very clear from the docs it seems.
The most common way to start a coroutine is like that:
var coroutineInstance = StartCoroutine(YourCoroutine(parameters));
The asignment part is optional
StartCoroutine((() => {
yield return null;
})());
```as an iife, of sorts
Nah that doesn't work
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?
good practice to assign coroutines in case you need to terminate them without having to destroy the GameObject
One step at a time, and on the topic of coroutines that's a good starting point if you need a timer
I've worked out what the current problem is & it's that the spear collider is inside of the other objects collider & when that object has a rigidbody, it goes crazy. i think all i need to do is disable collision with the parent once it's pierced the object
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?
show the rest of the code
,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
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
there a way to get a better view style on the folder? like windows detail view
what's the best channel to ask questions about proper component settings for camera/tile stuff?
Canvas stuff: #📲┃ui-ux
TIle stuff: #🖼️┃2d-tools
word ty ty
You can ctrl+scroll for that btw
i yern for the day that the grid view stops truncating file names too soon
would be nice if you could get a combination of the one-column view in that panel
with the left side folder browser
is that channel mostly just for the art side or the usage too?
i hate how common this is
just overflow, dammit
do ANYTHING other than truncate the name like we're on a goddamn DOS computer
8.3 all the way
I hate that i have to zoom all the way in or click to read the whole damn file name 😐
What idiot made it and felt this was acceptable
Substance Painter is really bad about this
I leave Unity on that "list view" perpetually
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
Seems like ReorderableList's drawElementBackgroundCallback is what you want
perfect! tx
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.)
This public bool IsGrounded => m_Rigidbody.IsTouching(ContactFilter);
is just a property, equivalent to writing
public bool IsGrounded
{
get
{
return m_Rigidbody.IsTouching(ContactFilter);
}
}```
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
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?
properties are methods disguised as fields
Yes, every time
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!
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.
incredible reaction progression guys
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
THose positions are going to be exactly the same
well firstPosition and secondPosition are gonna be the same value there
also why did you make it so complicated with extra methods like that
I guess I just do that xD, Is there any way to make this work? With Transforms?
you need a time step in between
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;
}```
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
("frame" but it's in FixedUpdate)
yes - physics frames
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!!
huh, ive never heard it called that
Frame is a pretty generic term that can mean any sort of window of operations.
It's true most of the time "frame" is referring to a rendered frame in the engine loop.
It's just easier to write frame than "physics update step" or whatever
i usually call them "physics ticks"
https://paste.ofcode.org/XtB7jvS6YSaYWzVaxdLDUh It doesnt work, did I make some kind of mistake in pasting and adding it?
why did you suddenly switch to Update
but uh - what doesn't work about it?
In the inspector the totalPosition is still 0, 0, 0
If you're in update then:
Vector3 velocity = difference / Time.fixedDeltaTime;```
This should be `Time.deltaTime` instead
is the target moving with Update or FixedUpdate?
because:
totalPosition = secondPosition - firstPosition;```
Sorry I changed it...
you're subtracting two vectors that don't do anything
Thanks, im blind
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
Im not sure, thanks, it works now!!!!
how do i create a script?
Do the !learn tutorials.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Look at the screenshot
i did
Then you saw it too
if you need this much help with stuff like how to make a script, maybe you should in fact do the tutorials
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
tbh they recently changed where the script creation button is, so even unity experts can be confused where it went
For me it still puts it at the top "Create C# Script"
what version of unity are you on?
yeah i did notice that, when i loaded up unity for the first time in ages it took me a sec as well but bearing in mind i was a unity beginner before (like spent less than 12h in the engine), then took a 2y break, came back to it after 2y and found it, it was confusing but not THAT confusing yk
2022.3.38f1
they changed it for unity 6
I see
how should i make a computer in my game?
The first step is to list out the requirements for what a "computer" is in your game.
Because without that, nobody knows.
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
how to enable and disable the display seems like the least of your worries if you want it to have "apps"
so i should just make UI in the right position of the monitor?
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?
@trail heart its fun to see you in one of the courses im using
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
the shape of the scene view camera is entirely dependent on the resolution and aspect ratio set for the game view window
Unity has the wheel collider component that you could look into
Oh neat
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
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
a dictionary? I'll look into that. thanks!
Its a generic collection where a unique id key maps to some object: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-9.0
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
your MoveEvent is an Action<bool> which means the event expects a bool parameter not a Vector2
thank you
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?
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)
the Input Actions asset i made is called PlayerController, but it doesn't seem to show up anywhere in the script
look at the import settings for that and check what you made the c# class name for it
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
click the asset, the inpsector will show the import settings. this is not an issue of not understanding input actions
Oh the tutorial didn't mention having to generate a c# class for it
it should have if the tutorial is showing that you need to create an instance of the class. link the tutorial
If you have specific course related questions, the forum and discord that were seen advertised earlier are useful because of the paywall
The lectures also have a comment section that often contain commonly asked questions
thank you!
Thank you so much for telling me about the wheel collider
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!
zoom
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
anyone know how to fix this?
remove VC package restart unity
If you use UVC then idk switch to git lol
thanks
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
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?
Start using Debug.Log and printing what's happening
Yeah but idk what to log in the bullet
log when it detects an enemy and does damage
and how much health the enemy has
and how much damage it's doing
and which collider you hit
the enemy

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
so it hit the collider extra 2 times
Which collider? Does your enemy have multiple colliders?
it has 2, but only 1 has trigger enabled
but is the bullet a trigger?
yes
then it doesn't matter
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
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
Just basing off this, make your on trigger a bit bigger than the other one so it detects the collision, then has the collision
Use layer based collisions to ensure the proper colliders are only interacting with the proper colliders.
fixed it, i just made another gameobject with the collison collider without a layer and used layers instead of tags
thanks
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
From what?
An int?
A byte array?
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
I'm starting to feel stupid... Why does the object with the Rigidbody attached not send the debug message on entering the other BoxCollider
how are you moving it ?seems locked
For debug purposes, it's just gonna rotate endlessly.
you should not move a rigidbody with translate
& not in update either
so what should I do instead?
reference the rigidbody component and access its methods for moving, addforce or velocity
use fixedupdate
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
how would changing from translate to velocity at all make it "go all over the place"
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
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
what are the speeds in the inspector set to ? also which object are you trying to Collide with to have that OnCollisionStay
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
I'm such a freaking idiot...
I muted the console.
Don't debug at 4 am, kids.
@rich adder thank you so much tho!
*tired
but yeah 
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?
Alright, I'll move it there. Thanks for reminding
Im realizing so many problems in unity are just overlooking one of a dozen details that all go into making something work as expected
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
Get a reference like any other component
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
yes that's wrong
nah, the youtube tutorial you followed just named the generated c# class the same as the existing component which made that more confusing
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
lol i just found out
InputField.textcomponent.text```
and
```cs
InputField.text```might be different
somehow they will add a zero whitespace there
Yes, the child TextMeshProUGUI uses a zero-width space for layout purposes, and should not be referenced.
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
you set the listeners up like this
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
You would now set up your listeners like this
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
Yes
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
Can someone tell me how do i make a button that triggers another animation on the UI
a physical world button? UI? a 3d? 2d ? you have to be more descriptive. Buttons are vague in unity
Oh i got it
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...
sounds like the gameobject itself is disabled
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
show the prefab you are trying to spawn
Debug.log before the play, see what is going on
okie! Just a sec. Thanks for helping btw!
Debug.Log($"{name} is active {gameObject.activeSelf} and coinSFX state : { coinSFX.enabled} to play")
are you sure this object is not getting destroyed or disabled in the same frame?
let me try removing the disable command
you might be better off playing the sound from elsewhere if you don't need spatial 3d sound
do you have any recommendation? I am kinda new to Unity so I am not sure how should I do that. Should I like create a empty game object and put a scipt there?
Singleton usually so you can just call for example
SoundManager.Instance.PlaySound(someSoundtoPlay)
//Sound manager script
public void PlaySound(AudioClip clip){ audioSource.PlayOneShot(clip);
https://gamedevbeginner.com/singletons-in-unity-the-right-way/#why_use_singletons
Thanks!! Much appreciate for the beginner article!
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?
Hey :)
You need to return (return;) within the first if block, otherwise backCamEnabled will be set to false first, and then back to true right after in the next if statement.
Alternatively, you can use Else in place of the second block
To ensure only one of them gets executed
Oh, never thought the problem could be in return;
Previous language didn't require that D:
Oh, it works now, thanks!
Returning just ensures that the code doesn't continue. In your case you only want to evaluate one of the two if blocks