@aspvect1 muted
Reason: if you want to continue posting here you will need to be less antagonistic. Follow basic posting etiquette, don't cross-post, and re-read our conduct if you have trouble.
Duration: 23 hours, 59 minutes and 59 seconds
1 messages · Page 782 of 1
@aspvect1 muted
Reason: if you want to continue posting here you will need to be less antagonistic. Follow basic posting etiquette, don't cross-post, and re-read our conduct if you have trouble.
Duration: 23 hours, 59 minutes and 59 seconds
Hi, is the example here bugged? https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.7/manual/advanced-topics/message-system/rpc.html#completing-the-ping-example
the call to PingRpc should be PingRpc(1, new RpcParams()); instead of PingRpc() ?
how would i get LookAt() to have a -90 offset on whatever the target is?
Looks like an error unless they have an overload somewhere
probably just an oversight. in the past the ngo docs were maintained by like one person, not sure if thats changed now.
also sucks to see they moved the docs to the Packages site. it looks like ass now
i wouldnt be too concerned about errors like that. its more of just a showcase of how you can use it. Seems like they probably copied the code, initially writing it as a method with no params and just forgot to update that part. the PongRpc looks correct
-90 what offset exactly?
a -90 degree offset? looking at a point -90 units offset?
this is the best thing ive seen all day
Hi i need help with unity scripting I have it all installed with visual studio but when i look for create C# script it dosent show can someone help me with this?
Have you checked the code editor in preference?
https://docs.unity3d.com/6000.0/Documentation/Manual/Preferences.html#external-tools
That menu item is just called "MonoBehaviour Script" in newer Unity versions
i found it that all im trying to do is just make a button and I cant do something simple and i follow tutorials and did they change a bunch of stuff last time in the past few weeks?
Im trying to find the stuff i learned in school but everything is just not there
^^^^ did you check this
and the loadscene prompt on click is it named something else?
is there an issue why the Scenemanager is not green?
!ide 👇
If your IDE is not autocompleting code or underlining errors, please configure it.
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
what is this? is there other stuff i need to install that needed to be install
follow the relevant guide and find out
Then what?
Then profit
You can call transform.Rotate after calling LookAt to "add" to the rotation. Is it 2D or 3D?
try restarting your computer? that shouldn't be an issue lol
they left the server
I'm searching about setting predetermined value on a field in parent from child (scriptable object), and i cannot remember one of the method the AI suggests.
what i get is, either, well assign it normally in child or using the Reset() method
however there is something in my first search that i cannot remember the exact syntax, and i cant get the same result on google AI
public class ChildClassSO : ParentClassSO
{
(?)private void ParentClassSO
{
parentField1 = ...
parentField2 = ...
}
}
it is assigning from inside a method, i closed that google search tab, what is it about ?
It's really not clear what you're asking here. And the code snippet you shared doesn't make sense
At what point in the lifecycle of the object do you want to set the values?
And are you sure you want to be setting fields? Why fields if you're going to set them to "predetermined" values?
i must've missed this step 😔
Hello! Is it possible to play a video backwards using Video Player? I tried but it seems that it only goes forward
Did you try changing the playback speed to negative?
It clamps it to 0
Yeah, doc says
Support for negative values is platform dependent.
It doesn't work for android?
No idea
But yeah I'd assume that if it's limited on some platforms then it would be mobile
Seems like you'd need to manually adjust the frame
Thanks. I'll try
it works, but it has different speed from normal playback
void Update()
{
if (reverse)
{
accumulator += Time.deltaTime;
if (accumulator >= 1f / frameRate)
{
videoPlayer.frame--;
Debug.Log("frame change");
accumulator = 0;
if (videoPlayer.frame <= 0)
{
reverse = false;
videoPlayer.Play();
}
}
}
else if (videoPlayer.frame >= (long) clip.frameCount - 1)
{
reverse = true;
}
}
It should be something like cs while (accumulator >= 1f / frameRate) { ... accumulator -= 1f / frameRate; // Instead of accumulator = 0 ... }
Currently you are only advancing max 1 video frame per Update
A while loop allows it to catch up if it should play multiple video frames during this Update
Thanks, but it starts to play forward at some point when it should be in reverse
At some point?
Is it just this?
if (videoPlayer.frame <= 0)
{
reverse = false;
videoPlayer.Play();
}```
I don't see anything else setting reverse to false here
Yeah, it's supposed to play forward when it reaches the start, but it starts to play forward in the middle of playing in reverse
can you show the current code
[SerializeField] private VideoPlayer videoPlayer;
[SerializeField] private VideoClip clip;
[SerializeField] private float frameRate = 64f;
private bool reverse = false;
private float accumulator;
private void Start()
{
videoPlayer.clip = clip;
videoPlayer.Play();
}
void Update()
{
if (reverse)
{
accumulator += Time.deltaTime;
while (accumulator >= 1f / frameRate)
{
videoPlayer.frame--;
Debug.Log("frame change");
accumulator -= 1f / frameRate;
if (videoPlayer.frame <= 0)
{
reverse = false;
videoPlayer.Play();
}
}
}
else if (videoPlayer.frame >= (long) clip.frameCount - 1)
{
reverse = true;
}
}
i don't see anything that would cause that, but i do notice that if you have a long frame when near 0 it'll keep going to negative frames
Is the video playing while you are also adjusting the frames manually?
I haven't used video player but that might be causing an issue
Do you need audio?
Maybe try doing both forward and reverse playback by setting the frame
IsPlaying is set to false when playing reverse
So there's more code
No, I just display properties of a video player
Might wanna add a break here
if (videoPlayer.frame <= 0)
{
reverse = false;
videoPlayer.Play();
break;
}```
So it stops without going to the negatives
Stops reversing, i mean
It is getting stopped at some point (video length is 5 seconds).
I don't see anything that would stop it. Maybe some quirk of videoplayer I don't know about
Do you have VideoPlayer.isLooping enabled or no?
It's disabled
I enabled loop and skip on drop and it's working
But it's slower than playing in forward
Without Skip on drop it just loops
Are you sure the video player is not playing when reverse is true?
I don't see you stopping it anywhere
If it plays forward while you manually adjust the frames backwards then I wouldn't expect it to have the correct speed
well videoPlayer.IsPlaying property shows false while in reverse
Just try calling Pause when you set reverse to true
Another thing to try is to convert your code from using frame to directly modifying time
So pretty much videoPlayer.time -= deltaTime instead of the delta accumulation etc.
I tried it but it's doesn't apply changes
it doesn't affect
Show what you tried
private void Start()
{
videoPlayer.clip = clip;
videoPlayer.Play();
videoPlayer.loopPointReached += EndLoop;
}
void EndLoop(VideoPlayer vp)
{
reverse = true;
videoPlayer.Pause();
}
void Update()
{
if (reverse)
{
videoPlayer.time -= Time.deltaTime;
if (videoPlayer.time <= 0)
{
reverse = false;
videoPlayer.Play();
}
}
}
in debug videoPlayer.time -= Time.deltaTime is called when in reverse but nothing changes
Actually yeah I just took a closer look at the time docs and I don't think it's meant to be used for this
The only hack I can think of right now is to control both forward and reversed playback manually with frame (and with playback paused)
No idea why it wouldn't be the correct speed tho
The logic looked fine
the context is furniture in 2D game that player can place, i want to add decoration which do not have all 4 facing direction unlike furniture, but i don't want to copy paste same data for all 4, so I'm wondering can i make a child and fill just one data and automatically it will assign it to all 4 direction data of parent ?
I got it now that you need extra editor script to add button to run the method (the snippet) that will update the parent data during editing from inspector.
Did you read the docs about setting time? https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Video.VideoPlayer-time.html
It says, that it will add any additional change of the setting of time to a queue and waits for previous once before it continues. Could it be, that the dequeue is happening slower than your update loop is running? So it will "lag" behind?
void Update()
{
if (isReversing)
{
videoPlayer.Pause();
double newTime = videoPlayer.time - Time.deltaTime;
if (newTime < 0)
{
newTime = 0;
isReversing = false;
}
videoPlayer.time = newTime;
videoPlayer.Play();
}
}
This is what I came up with thats "somehow" working. But you can see, that it struggles with the playback sometimes not reversing or taking sometime before it actually updates the frames and then keeps on reversing. From what I read also on Renderheads AVPro Video package, its just a huge issue to play in reverse because the player will always have to expensively compute the previous frames.
Here are some tips what you could do, but depending on the video, if its not dynamic, you could also think about creating a reversed version and sync two videoplayers for example, which still might be less expensive than running a forward played video backwards.
https://www.renderheads.com/content/docs/AVProVideo/articles/feature-seeking-playbackrate.html?q=Reverse#:~:text=If you want to start changing the playback rate%2C play in reverse%2C allow fast scrubbing%2C or have fast frame accurate seeking then you may run into issues where the playback becomes extremely slow or the seeking is not accurate.
are there, like, intended methods for animation transition to occur like last/new animations are not playing?
Are you talking about animator transitions between two states? Or what exactly?
yes
currently I am modifying speed of the state to get the effect but it's kinda cursed
Maybe you can show, what you are trying to achieve with code
right, that's not really a code question but more about animator
what I am trying to achieve is that walking > stun animation transition like walking is halted - so less movement on legs since they won't make much sense
and it works if I set walking state speed zero before transitioning but that looks like there should be a proper way to do so
anyway at least that works, now I see the part which does not work
And you cant decrease the transition to "stun" to make that work?
#🏃┃animation but maybe continue over there, as you said. thats some kind of animator question
that would change the look of transition
thanks for linking that channel, I ll use it next time I get animator issue
actually I would go there rn cause my another issue got code involved but not about code
somehow suddenly i cant drag multiple audio clips into my AudioClip[] in the inspector, anyone know how to fix?
make sure no console errors, make sure types correct
thanks, yeh still no luck, so tedious, i can drag 1 by 1
are you dragging them in the variable name?
dragging them as usual onto variable name yeh
yeh must be a bug in this unity, arrays acting very weird
is there a way in the graph toolkit to have ctx.AddOption with some enum, but only conditionally show?
for example, i have a way for my importer to tell the type of a ScriptableObject game state key, and want it to show the appropriate enum options, such as operations related to bools if the key type is bool, int operations for ints, etc.
essentially, i want to be able to be able to have this, but have it be able to be conditional which actually shows the proper enum based on the key type.
ctx.AddOption<IntCompareOp>("IntOp").WithDefaultValue(IntCompareOp.Equals);
ctx.AddOption<FloatCompareOp>("FloatOp").WithDefaultValue(FloatCompareOp.Equals);
ctx.AddOption<StringCompareOp>("StringOp").WithDefaultValue(StringCompareOp.Equals);```
however, i don't think there's a built in thing for options such as .VisibleIf, at least docs-wise.
What does "direction data" look like exactly?
I am struggling with twitch integration with unity I dont know if the solutions im trying are too old or what but they keep failing at the user auth stage. Does anyone know of a stable solution? No matter what I do in terms of auth token ,the channel name ,the Client ID or OAuth Redirect URLs I cant seem to get right.
what version are you on?
What do you use to call the API? Manual web requests or an SDK of some sort
I’m using the Dan Qzq Unity Twitch Chat Interactions library. It handles most of the OAuth, chat connection, and API calls for me, so I don’t make manual web requests. The library wraps the Twitch API in C# methods I can call from Unity.
https://github.com/danqzq/unity-twitch-chat-interactions/tree/main
Hi , could somebody please help me wih my projekt? I need to know how to use varibles in two differnt scripts .
would you mind showing me in vc?
ok , have a good day
The last commit was 3 days ago, so it likely is not outdated.
If you followed their setup steps and it doesn't work, check errors. If that doesn't work, contact the dev
Choose the best way to reference other variables.
What is the good way to store whether a monster is dead between scenes?
Either of the first two are pretty standard
yhym ty
Is it even worth it caching WaitForSeconds
Like, i have to have a field for storing WaitForSeconds cuz unity recommends caching it now
Like, whats the point????
I did it here, but with other transitions, like in this pic
But here i havent cuz i didnt feel like its worth it
is the impact even high enough to even consider caching them?
If you're going to reuse something over and over, such as a WaitForSeconds object, there's no harm in caching them.
Creating an instance of WaitForSeconds takes time and provides zero benefit. It's literally a free performance increase
question is:
Is the performance increase worth having a field for each corotine
"Is the benefit worth zero effort and no functional change"
yes
Also, the fact that you're creating it in the function means that you're still making a new one every time
So you're not even actually getting a benefit
its not a "zero effort" for me
for me it means i need to clog classes with additional fields
so i have to think if its worth it
Also another question, can i reuse same object for multiple corotines, what if i use 1 object at the same time
The entire point is to create the wait one time and reuse it
you don't need a field. Do you mean a local variable?
yes
it really depends how often you're doing this, but it's good to be in the habit of reusing whenever possible. Garbage collection is an insidious silent killer of performance.
you could use pooling to have more than one if needed and cache that amount
Create a static object that stores them for reuse. Nice and tucked away. 
But realistically, if your game is small, then it's whatever. It's not going to be the thing that makes your game unplayable.
But if you're running that function across many objects at once (AI looking for the closet object), then yes it will matter.
I guess
you could extend this with a dictionary or array to get specific time waitforseconds and create new ones if not existent yet and then you can just pool catch them to be used
Yeah no im not implementing that.
I feel like using fields would be easier to handle and they could act as "Configs" so i can change transition speeds and stuff without editing the class with logic
well, it would just be something like
Dictionary<float, WaitForSeconds>();
//and then check against in your GetMethod()
myWaitForSecondPool.TryGetValue(seconds, out var wait)
//where you can return or create the needed one
yield return YourNamespace.WaitForSeconds.GetMethod(1f); //Or whatever
And changing transition speeds could still be just your field instead of 1f in my example
how would i get the gameobject that the script is attached to
.gameObject
Or just gameObject
mb i was doing ||public GameObject Character = gameObject;||
https://paste.mod.gg/xntuifjdpnjk/0\
why my player dont take damage if he hit that object?
A tool for sharing your source code with the world!
!code Dont send plaintext codes
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
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.
mb
can you help tho?
The three commandments of OnTriggerEnter2D:
isTrigger on at least one of themRigidbody2D on at least one of themWhats Health?
A tool for sharing your source code with the world!
nvm im dumb its just debug it instand of destroy it
how do i make an ai that will chase me?
that's a pretty broad topic, start with google
agent.destination = player.transform.position;```
There are a bunch of ways to go about it. each one having numerous steps
No, this is forbidden: you can't access this inside of a field initializer
(and even if C# let you do that, Unity would not have had a chance to set the object up yet)
i'm pretty sure it's illegal to give a MonoBehaviour a constructor that tries to access Unity properties
hi how do i start making 2d games because i dont find good tutorials
There are plenty of tutorials, the fact you haven't found "good" tutorials is silly.
If you want to learn Unity in general, you can go through Unity's own tutorials:
!learn
Over 750 hours of free live and on-demand learning content for all levels of experience!
would this work without mathf. ?
What do you mean by "without mathf"? What would Mathf be doing here?
are you getting errors?
i mean whats even happening lol
youre being a bit too vague for us to help
theres no errors
its just supposed to change the light intensity off of a variable thats it
the bool turns on and works but the intensity never changes
why are you using fixedDeltaTime inside of Update? that's going to be affected by the framerate
but should still work?
Try logging it after you change it
yeah that doesnt help, logs still said everything should be working
its only the one line I need help with
theres some type of issue with that specific thing
What did the log say
Did the value increase when you logged it?
no
What did you log, and where?
the value itself has not changed at all, I see it in the inspector
I logged when the bool is fully on and when it was told to go on, and both went off
the light intensity stays at 0
Show your code with the logs included
it has something to do with the time.fixeddeltatime it worked without it
I need it to work overtime though
Instead of just logging text that tells you nothing useful, log the value of mylight.intensity
And you realize that there is zero indication that what you're looking at in the inspector is even the same light
Log it.
Stop assuming, check.
I literally said the problem is in the line of code here
And I asked you what mathf would have to do with this and got no answer. How about you log the value and see if it's changing
its not
Do the logs show that?
mathf would be to change it overtime
Mathf is a mathematics library
smh nvm
So, when you log the value of mylight.intensity, what does it say
You'll have a much more pleasant time coding after you configure your !ide
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Thanks
why my death animation not working? its showing at all the the first frame of the death animation and when its dead shows nothing heres the codehttps://paste.mod.gg/ucvvolxhsrhv/0
A tool for sharing your source code with the world!
(the ball is the enemy)
one issue is that death isn't a trigger. You configured it as a boolean
so how i fix?
delete "death" boolean in the animator parameters, add "death" trigger, then fix the transition to use the trigger
or if death is intended as a boolean, edit code to use SetBool instead
right now, the "Death" parameter starts out true, and nothing causes it to ever become false
so the transition from 'Any State' to 'death' is always valid
(and by default, this transition is allowed to run even if you're already in the 'death' state)
therefore, it restarts the animation every frame
its working thanks yall
any idea on this? this is almost the last thing i need before my entire dialogue system will finally be finished.
It seems that no matter what I do my jump animation always either plays for one frame then goes back to idle, running, or walking animation in mid air. Ive tried to do everything in my power to have the jump animation prioritized first and foremost but it never does
Can someone help me wit this?
show us your animator
Nothing is eally going on in there. Im using alot of animator.Play in the script. Everytime I tried to use the animator it would turn into a massive spider web and it would not work out the way I want it to
I was hoping to use booleans in the animator to prevent the grounded animations like idle, walk, and run from playing but no matter what it doesnt do as I intended
If you don't have any transitions, then the animator will only change states if you tell it to via Play(). so, go ahead and share that
Its super messy
just ignore that and go to the animation methods
Thats where I handle all my animations
I would make sure that onGround is getting set correctly
notably, you're using a pretty long raycast in getisGrounded
and you don't check if your velocity is negative (or at least not positive)
so this method will say you're grounded even while you're moving up at the start of your jump
which will immediately cause you to play a walking/idle/running animation
YEah thats why what i was trying to do is have the box collider work along side the raycast for whenever Im off the groud but also have another bool that determines when Im off the ground by only using the box collider
thats why I have the onGround
oh, isGrounded and onGround are two different variables
You should still check what the actual value is. Maybe log the relevant values at the top of Animation2().
True Im gonna actually make the raycast longer to test something
Can confirm in the inspector that the onGround is unchecked first when I jump then the isGrounded
I do!
So this is a platform fighter and when you airdash into the ledge and have the collider collide with the ground you become grounded even though your in the air and so having raycast allows me to pick and choice which true or false things happen when I jump off the ground or when I land
Like resetting the jump count or airdash count
requiring both the raycast and the box collider to touch the ground makes it so that I still need to land on top to reset jumps but prevent jump count resetting wwhen jumping next to the ledge
Also I still couldnt figure out how to have the jump take priority. I actually solved this issue before back when I was only using the box collider and not using a raycast along side the collider
but honestly I have no idea how I even solved that
or at least I dont understand how it fixed it. I tried replicating the same thing but nothing happens now
is there a neater way to write this
if (IsGrounded)
{
newVel = new Vector3();
}```
Initially set to Vector3.zero and set the y value if it isnt grounded
Isnt that js reversing it
You asked for neater . . .
The only thing that changes is the y value, so change it if you're not grounded . . .
why does it says impact not exist when it is? https://paste.mod.gg/enmrpcnyhrwt/0
A tool for sharing your source code with the world!
Are you looking at the animator it's trying to call the parameter on? Are you sure your parameter is named impact and not something like impact with an extra space at the end?
Try logging targetAnimator and see what object it's detecting
logic seems backwards. Bullet has an animator with "impact", but your code for bullet tries to play "impact" on Enemy. Enemy's animator probably doesn't have "impact"
Dude I can't figure out why the idle, walk, and run animations take such high priority over only the first jump? 😭😭
it plays for like one frame then it stops
when i make a clone of Droplet prefab instance, the clone's Bullet Pool Container starts out empty
like this
While it's in the name just a heads up that Clone isn't reallyyy used much in documentation/reference so might confuse people, usually Instance is used. With that in mind, When you say your "making a clone of a prefab instance", are you instansiating a prefab asset, or a prefab instance?
I am instantiating the prefab instance
ok so just a heads up, Instance would be the thing that exists in the scene, either placed manually in editor mode or spawned via code. a reference to a Prefab from your /Assets/ would be a Prefab Asset
mentioning this because using the right terms better for explaining and researching
on that note
Ideally you'd be dragging in the prefab from /Assets, not one that's just in the scene
isn't the clone spawned via code?
so it should be called the prefab instance no?
"Instance would be the thing that exists in the scene, either placed manually in editor mode** or spawned via code**"
oh wait, the clone is the instance
mb
Yes, your problematic one is an instance, but the one your referencing in your serializedfield is currently also an instance from the scene, which you might want to be instead a reference to the prefab Asset (?)
It should be an exact copy of whatever was instantiated
both in the top pic are prefab instances
alright
you probably want to be referencing the prefab asset in your pool
Is there some way to make a dynamic rigidbody completely immovable without setting it to kinematic OR applying constraints?
Is there a specific reason why the other two are not viable solutions?
you can set its velocity/position to 0/whereever you want it to stay every frame
In knowing so, the solution can better cater towards what you're needing.
Mainly I want to see if such a thing is possible with dynamic bodies being "free"
every fixed update tick to be specific
Would that cause jitter?
When collided with
What do you mean by "free". Constraints would seem like exactly what you'd want
it shouldnt if you set it in fixed update
i think
idk try it and see
Oh, another thing I want to know is if it's possible for two dynamic bodies to not push each other if they move into each other
you can make them elastic and bounce off each other
like how exactly would they behave when they collide
do they both just stop completely?
That would be a different kind of physics so unless you implement it yourself, you'll probably get some level of shoving unless they're so massive that it's practically impossible to be moved etc
even still that only works if one object is massive and one isnt...
not really a great solution here
You know how character controllers slide along a wall if their movement is partially into it? Something like that, but with two bodies. They would slide off each other
its why kinematic and static exist
uh im struggling to imagine how thats supposed to look with two moving bodies
can u give an example
If it helps, I have a player controller in mind where their movement is pretty rigid, like what happens with character controllers, but they can situationally act on or apply forces.
My thinking is probably a custom controller that has a character controller as a baseline, but I'm trying to see if finessing a rigidbody could work.
i suppose you can directly set velocity in physics tic every frame and then stop doing so when you situationally act on or apply other forces
thats prolly the closest to what you want
Gotcha, yeah I tried that, but two moving dynamic bodies can push each other in that situation. I probably just need to switch over to using a character controller and code the specifics I want
probably, even in your player wall example the wall pushes back on the player which is what causes that sliding motion
if i have two collide in this way theyd slide off, though it looks more like pushing since its a very short collision
Gotcha. Do you think using one of those 1st/3rd person starter assets would speed things along, or should I go full custom with a character controller?
thats kinda beyond my area of expertise as i usually make my own rigidbody scripts instead of messing with the unity controller stuff
so hopefully someone else can help u lol
Ah lol no worries
If anything, without having to reinvent an entire system, you could probably have some other object with a kinematic body follow each the players (using a parent constraint component) that would prohibit the other objects from pushing it. Whilst ignoring it's own player object, that is.
This implies that object would have some collider slightly larger than the players to prohibit any interaction between players.
Oh interesting, and then maybe it can be disabled if it collides with something that should inflict and be affected by pushing forces
[SerializeField] BulletPool bulletPoolContainer;
void update(){
// if a certain condition is met
GameObject Tempbullet = bulletPoolContainer.DropletBulletpool.Get();
}```
public class BulletPool : MonoBehaviour
{
[SerializeField] private GameObject _dropletPrefab;
public ObjectPool<GameObject> DropletBulletpool;
private void Start()
{
DropletBulletpool = new ObjectPool<GameObject>(CreateDropletBullet, GetDropletBulletFromPool,
ReturningDucktoPool, OnDestroyDuck, true, 20, 10);
}
}```
Tempbullet shouldn't be null even if the DropletBulletpool has nothing in it because the pooling mechanism creates an instance and returns it right?
if thats how you defined it to work, sure
Best check the object pool doc
you define the method CreateDropletBullet, it does what you tell it to
{
GameObject DropletBullet = Instantiate(_dropletPrefab, _dropletPrefab.transform.position, Quaternion.identity);
return DropletBullet;
}```
if something isn't working as you expect, add logs or specify your error. I have doubts the issue is what you think it is
guess what, it's not working, apparently Tempbullet ain't working
null reference
An nre occurs if members are not accessible. If it's occurring on line 27, the container or pool may be null
it's not reaching the part of the BulletPool which creates an instance
the pool is supposed to be null initially
Properly post code so that I do not have to squint and manually type characters (no images please unless absolutely necessary - ide/editor bugcs Debug.Log($"Container: {bulletPollContainer}"); Debug.Log($"Pool: {bulletPollContainer.DropletBulletpool}"); Debug.Log($"Container: {bulletPollContainer}");
using NUnit.Framework;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
public class EnemyCollision : MonoBehaviour
{
[SerializeField] string DuckTag;
private List<Transform> EnemyList;
[SerializeField] Bullet bullet;
[SerializeField] float ReloadTime;
[SerializeField] float Damage;
[SerializeField] float BulletSpeed;
[SerializeField] float BlastRadius;
[SerializeField] BulletPool bulletPoolContainer;
private float _reloadTime = 0.0f;
private void Start()
{
EnemyList = new List<Transform>();
}
private void Update()
{
//if ready to shoot and there are enemies present in range
if (_reloadTime >= ReloadTime && EnemyList.Count != 0)
{
Debug.Log($"Container: {bulletPoolContainer}");
Debug.Log($"Pool: {bulletPoolContainer.DropletBulletpool}");
//create a bullet
GameObject Tempbullet = bulletPoolContainer.DropletBulletpool.Get();
Debug.Log($"The Tempbullet is: {Tempbullet.tag}");
Tempbullet.SetActive(true);
//Bullet Tempbullet = Instantiate(bullet, this.transform.position, Quaternion.identity);
Bullet bullet = Tempbullet.GetComponent<Bullet>();
bullet.SetPool(bulletPoolContainer.DropletBulletpool);
bullet.Initialise(EnemyList[0], Damage, BulletSpeed, BlastRadius);
_reloadTime = 0.0f;
}
_reloadTime += Time.deltaTime;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == DuckTag)
{
Debug.Log("Duck was detected.");
EnemyList.Add(collision.transform);
}
}
private void OnTriggerExit2D(Collider2D collision)
{
EnemyList.RemoveAt(0);
}
}```
using UnityEngine;
using UnityEngine.Pool;
public class BulletPool : MonoBehaviour
{
[SerializeField] public GameObject _dropletPrefab;
public ObjectPool<GameObject> DropletBulletpool;
private void Start()
{
Debug.Log("Reached here.");
DropletBulletpool = new ObjectPool<GameObject>(CreateDropletBullet, GetDropletBulletFromPool,
ReturningDucktoPool, OnDestroyDuck, true, 20, 10);
}
GameObject CreateDropletBullet()
{
GameObject DropletBullet = Instantiate(_dropletPrefab, _dropletPrefab.transform.position, Quaternion.identity);
return DropletBullet;
}
private void GetDropletBulletFromPool(GameObject droplet)
{
droplet.SetActive(true);
}
private void ReturningDucktoPool(GameObject droplet)
{
droplet.SetActive(false);
}
private void OnDestroyDuck(GameObject droplet)
{
Destroy(droplet);
}
}
What did the logs print?
Container: Pool (BulletPool)
UnityEngine.Debug:Log (object)
EnemyCollision:Update () (at Assets/Scripts/Collision/EnemyCollision/EnemyCollision.cs:26)
why do you think this
Pool:
UnityEngine.Debug:Log (object)
EnemyCollision:Update () (at Assets/Scripts/Collision/EnemyCollision/EnemyCollision.cs:27)
cus initially, there are no bullets at start, it's only when the enemy enters range, that it starts firing so although, the pool is instantialised, there are no instances present in it
empty != null
Blank after pool implies the pool was null
is the BulletPool object you are referencing a prefab or an object in the scene
its the prefab asset
that's the issue then, if it isn't in the scene then Start has never been called on it therefore it never instantiates the actual ObjectPool object
Just for clarity, let's refer to the term prefab as objects in the scene. Once an object is instantiated from a prefab, it's an instance of that prefab and not actually a prefab. This applies to objects already in the scene as well. If they're already in the scene, they aren't refer to as prefabs.
during runtime though, a Droplet is cloned and is present on the scene, so it does run whatever is present in Start
something else is doing that then. or you've got a BulletPool in the scene which is what you would need to be referencing instead
so, it does end up printing this
Perhaps the object that had it's start method called isn't the same object?
exactly
the prefabs are referencing each other, so although the Droplet is instantiated, since the Pool isn't, it doesn't reference the Pool prefab
even if it did reference the Pool prefab, that prefab never has Start called on it
They're referencing prefabs.. not instances in the scene spawned from those prefabs just to be clear.
aren't i saying the same thing though? they aren't referencing instances, they are referencing the actual prefabs themselves
ya, it doesn't have a start function in it
so the "Pool" prefab does not have the "BulletPool" component on it? because that has a Start method that is only called when the object exists in the scene
no, more like it does have the script, it's just that the script itself doesn't have the start method in it
wth do i do then
so you're telling me this code right here, which clearly has a Start method, does not have a Start method?
ahh shiii, sry mb. you are right. i was talking about Bullet instead
why not then
i did have this setup before where the GameObjects were referencing each other, the Pool and Droplet in hierarchy
did not work though, cus the clones weren't referencing the Pool when instantiated
have the pool in the hierarchy. then, like i told you the day you first asked about doing this, have whatever spawns the turret objects pass the pool to the spawned turret objects when it instantiates them
it's still showing a null ref error
where
here
and did you actually do this or did you just expect you could clone the prefab and not pass the existing pool to the spawned objects
So just for clarity, on this line bulletPoolContainer.DropletBulletpool.Get the bulletPoolContainer (likely a prefab asset reference rather than the one you're expecting from the scene hierarchy) has it's member DropletBulletpool as null.
more like i am trying to pass the existing pool present in the hierarchy to the clones too, but it ain't happening
show how you tried to do that
yes
So instead of referencing the prefab assetbulletPoolContainer, actually reference the scene object.
I thought if i referenced the gameobjects in the hierarchy, their clones would reference each other too
like this?
so you didn't do what i said. i specifically called out passing the reference to the instantiated object and did not say "rely on cloning the object to still reference the right object" because doing that would mean you have to clone the scene object but ideally you would be cloning a prefab instead
Which object is the Pool object? Where is it located?
It should be an object in the scene (not an asset prefab)
see this
Make sure to save the scene
how do i do that
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
btw did you mean something like this?
public void SetPool(ObjectPool<GameObject> DropletBulletpool)
{
_dropletBulletpool = DropletBulletpool;
}
in the Bullet itself
cus i did set
private void Update()
{
//if ready to shoot and there are enemies present in range
if (_reloadTime >= ReloadTime && EnemyList.Count != 0)
{
Debug.Log($"Container: {bulletPoolContainer}");
Debug.Log($"Pool: {bulletPoolContainer.DropletBulletpool}");
//create a bullet
GameObject Tempbullet = bulletPoolContainer.DropletBulletpool.Get();
Debug.Log($"The Tempbullet is: {Tempbullet.tag}");
Tempbullet.SetActive(true);
//Bullet Tempbullet = Instantiate(bullet, this.transform.position, Quaternion.identity);
Bullet bullet = Tempbullet.GetComponent<Bullet>();
**bullet.SetPool(bulletPoolContainer.DropletBulletpool);**
bullet.Initialise(EnemyList[0], Damage, BulletSpeed, BlastRadius);
_reloadTime = 0.0f;
}
_reloadTime += Time.deltaTime;
}```
i did pass a reference to that pool then
and what about to the object that is literally throwing the NRE? because that's a different object
like it's literally the one you are posting code from. that needs the reference
so...i make a reference to the pool wherever the object which this Update() is present in is instantiated from?
yes, this object needs the reference to the existing BulletPool object. so pass it to this object when this object is spawned.
ahhh
this is the turret object, yes? that's what i told you to pass the pool to in the first place
wait, the turrets AND the bullets need to be present in the SAME pool!?
at no point did i say that the turrets need to be in the pool
i ain't applying pooling system to the turrets yet, only the bullets
they need a reference to it, not to be in it
wait lemme figure it out then
I noticed that when using a character controller, there's a gap between them and things they're colliding with. Walls and the ground are the big things where I'm seeing this. Any ideas on how to get it closer to actual touch?
pretty sure that's the skin width
Ah right. Any issues with the value being super low?
Why don't u mess with it and see how it turns out
@slender nymph @sour fulcrum thx, it's working now
how cooked is this?
should i make the bullet separate from the Droplet?
ah, right.
Hey there. i've been trying to experiment with a wall jump script, but i'm having trouble getting the oppisite Y rotation of the current Y rotation, which would make the character face their backside as soon as they performed a wall jump, but they aren't turning properly most of the time, especially when they're on 0 degree's you can't really say -0 to get the oppisite rotation
//If walljump triggered
if (playerJump.triggered)
{
//Only allow if can walljump and ishugging wall
if (isHuggingWall && canWallJump)
{
//Get forward
Vector3 playerForward = transform.forward * 40;
//Get new velocity
Vector3 wallJumpVelocity = -playerForward + new Vector3(0, 50, 0);
//Apply velocity
playerRigid.linearVelocity = wallJumpVelocity * 2;
//Play jump combo sound for now
playerSound.JumpComboSound(jumpCombo);
//Get current angleY
float currentRadY = transform.rotation.y;
float targetAngleY = -currentRadY * Mathf.Rad2Deg;
//Apply rotation
transform.rotation = quaternion.RotateY(-targetAngleY);
}
}
i could be mistaken but adding 180 to any current rotation will just go the other way, no?
Whatever the case is.. transform.rotation isn't referring to an Euler angle (degrees). You should not be using it as though it is such.
Yeah was gonna say what they are doing would be like facing 45° then -45° thats only a 90° angle not a 180°
I did try to add that but i think you would also have to wrap it around?
unity does all that
ahh, so if you set a value above maximum degree
unity does the job on the rotation values
got it
if im wrong someone will correct me but yeah it should resolve it into whatever its meant to be in the range
i've actually never 100% looked into it myself but i wanna say thats -360 to 360? since positive negative is used for direction?
I didn't get any errors so yeah, it should be like you described
For some reason at max i'm getting 60 degrees when i turn around completely, and thats about it
i'm definitely doing something wrong which sucks
getting 0 to 60 turning from start point to the right side to my back and from their it's minus
Did you remove the few lower lines that attempt to make use of the quaternion y component?
The quaternion consists of x, y, z and w components. It isn't likely what you think it is.
It isn't what you think it is
what the heck, it's x? why did i think it was y
wait nvm i'm just losing it, it is y
rotations are weird for complex reasons, generally you'd want to use
.rotation = Quaternion.Euler(x,y,z);
to handle it like you would position and scale
Yeah and just apply transform.rotation.x and z on the uneffected ones right?
reading them is the same yeah, just setting them needs some help
so it's perhaps the rotateY function you're suggesting is causing that. alright
i'll try it
A quaternion is a four-tuple of real numbers {x,y,z,w}. A quaternion is a mathematically convenient alternative to the euler angle representation.
...
Note that Unity expects Quaternions to be normalized.
The four components of a Quaternion are not what you think they are.
https://docs.unity3d.com/ScriptReference/Quaternion.html
ah so just complications i have yet to understand
hopefully this isn't a poor explaination but basicially unlike position and scale rotation fundementally has some context/history related to going from one value to another
because lets say you spin yourself to move north
there's multiple ways you could do that
ahhh you're refering to angulers right?
like how lerp has slerp, or smoothdamp has umm well it has it too with a certain name, which calculates the path of rotation
is that what you're talking about?
Most will never and would not want or have-a-need to ever understand https://en.wikipedia.org/wiki/Quaternion
Damn, yeah this is getting into some real math.
Logging the rotation property should immediately reveal that the numbers may not be what you'd expect.
it's very interesting tho. Get's complicated really fast, just read abit about it and nope, like you said, i don't need to learn math for this
lol
If you're wanting to see the current represented Euler value, you can use https://docs.unity3d.com/ScriptReference/Quaternion-eulerAngles.html but do understand that it can be represented in many ways (it'll not always be the same as in -90 might be 90 or some other value)
wait this might be it
lemme see
dude. eularAngle is the way to go, i'm getting much better values now
float currentRagY = transform.rotation.eulerAngles.y;
thanks for the help
When you read the .eulerAngles property, Unity converts the Quaternion's internal representation of the rotation to Euler angles. Because, there is more than one way to represent any given rotation using Euler angles, the values you read back out may be quite different from the values you assigned. This can cause confusion if you are trying to gradually increment the values to produce animation.
...
To avoid these kinds of problems, the recommended way to work with rotations is to avoid relying on consistent results when reading .eulerAngles [...]
Best to just keep a Vector 3 field. Modify and do arithmetics to said field. And write directly to the rotation property usingQuaternion.Eulerif you're needing to change the value. Else Quaterion has some common overloaded operations for adding or
subtracting rotations.
I'll have to spend some time on that to get the hang of it then
You would think this would work but i'm still getting inaccurate rotations
//Get reverseY
float reverseY = Quaternion.Inverse(transform.rotation).y * Mathf.Rad2Deg;
I would not think this would work at all
you should never be touching the .y of a Quaternion like this
You're still attempting to make use of the normalized quaternion y value.
Yeah it's the normalized value translated to degrees which gives off the illusion that i'm getting the actual degree but i'm inaccurately just grabbing the normals huh?
it's not a "normalized value". It's a quaternion component which doesn't relate directly to euler angles at all
Also:
Say no to euler angles
It's not the radian value of an angle. It's some normalized matrix value
https://docs.unity3d.com/ScriptReference/Quaternion.html
Go read what you're accessing there
Alright.
Should've snapped it with the w component as well to clearly identify that it's got more than 3 parts
It's weird tho. i'm getting half of the degrees right and the other half is just wrong.
As you can see. above 180 it doesn't go to minus like the actual objects rotation
What's the current code?
//Get current angleY
float angleY = transform.localRotation.eulerAngles.y;
Basically this.
Right, looks fine.
definitely much better yeah, although like i stated here it's not truly translating to the objects rotation
maybe the quaternion inverse would work this time? lemme try it
that seems to be correct
I'm going to step out of this one... Reminder: #💻┃code-beginner message
i see.
the true representation of the rotation is the quaternion. if you turn that into degrees, then there's not really a 'canonical' angle
obviously 720 isn't canonical, but is -90 or 270 more correct? if using negatives, should it be 180 or -180? etc
but it really doesn't matter if you're just doing math, just that you need to treat angles correctly.
alright i'm not religious but, prayers this will work
//Get current inverse angle
float angleYInverse = Quaternion.Inverse(transform.localRotation).eulerAngles.y;
and if you're using it to display stuff, it depends on what would be more useful to display
imo in the editor, negative angles would be better, and from code, yeah having non-negatives for debugging purposes seems to make sense
I see since the functions i'm calling are already calculating that properly
Yeah, definitely confusing for a beginner tho. Hence my initial confusion
rotations are confusing in general 😮💨
i mean, on the surface, yes it's pretty intuitive. but once you start getting into the math and representations and algorithms.. there's a lot more than one might expect
definitely. i'm honestly alot more comfortable with 3D space forward and right with transform to be honest and you can do alot of cool stuff with that
yeah just alot of road bumps
it's a really common mistake to make
oh wait, I thought you were doing this :p
transform.rotation.y
(that's the really common one)
they had something similar at one point
but yeah, individual Euler angles can be very misleading
your Y rotation affects the meaning of your X and Z rotations, and your X rotation affects the meaning of your Z rotation
Yup i did.
oh god..
I rarely actually use them directly
Quaternion and Vector3 have many useful methods
e.g. Vector3.SignedAngle
Usually you can get away if you only modify like Y and X, but once you touch Z then euler just lies to you
can get away with a lot more things in 2D that's for sure
I try to never actually modify the euler angles
this is a code channel
oh sorry, I got the wrong channel.
SecondsSet += seconds;
if (SecondsSet > 86400) SecondsSet = 0;
int h = SecondsSet / 3600;
int m = SecondsSet % 3600 / 60;
int s = SecondsSet % 60;
PlaceholderCountdownText.text = $"{h:D2}:{m:D2}:{s:D2}";
SecondsRemaining = SecondsSet;
long unixNow = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
targetUnix = unixNow + Mathf.RoundToInt(SecondsRemaining);
which part of this code is the most performance reducing?
i notice a total 1 second freeze when i do this function, even if seconds is 60s or 6000s, same 1 s freeze
also, when doing it for the first time*
after that it does not lag anymore, weird, cant replicate on pc
only on android
is it that accessing UtcNow initializes smth ?
Almost certainly the allocation and garbage collection of the string
But you should use the profiler to confirm
ah so once its garbage collected it doesnt lag anymore, is that why it doesnt lag the more you do it after?
couldn't it also possibly be the redrawing of the canvas?
No, this will create garbage every time it runs
You need to use the profiler.
but it doesnt lag every time, only the first time i click
let me check
no its not and you would see a large gc collect operation if the lag was the garbage collector working
I think more context is needed
For starters a frame with the lag spike sorted by cpu time.
foreach (string word in answer)
{
if (target.Contains(word, StringComparer.OrdinalIgnoreCase))
{
Debug.Log("Found word: " + word);
}
else
{
Debug.Log("Not found: " + word);
}
}
return true; // All words matched
}```
I have a list of string (answer) that I want to check if all the elements in it matches the elements in another list of string (target)
it isn't working as intended as there are some words that are present yet get detected as not found
any help with that?
Show an example of the two lists that don't work as intended
kinda smells like the just-in-time (JIT) compiler running, but that's a really long hitch
so what can i do
ill try and see later on
You need to find the frame with the spike and look at that.
İ am making a fps game and i used cameta stacking for weapon clipping. The camers that renders the weapon layer cause performance issue. And yes i am sure that main camera doesnt render the weapon layer.
Is there any optimization trick about that
renderer features
avoids the 2 camera thing entirely
also mix that in with reactive occlusion through ik and you get a nice looking anti clipping system
https://cdn.discordapp.com/attachments/1390716509638098995/1441555951592144996/occlusion.mp4?ex=693de899&is=693c9719&hm=8450cbfb9cab3e2b9c0c7e193f5a936d32e13c7c996b547195e69bdf0356703a& thats what i did personally and it works fine, you can still use the 2 camera trick if you want seperate fov controls for your weapon and main camera.
Nice i will give it a try
Thanks for the respond
Btw did u make it using animation rigging?
pulling the weapon back as you approach a wall looks really nice
lovely work... Co-routines for the camera shake? or some Cinemachine built in stuff?
per frame procedural approach relying on time.detlatime rather than coroutines
it works by progressively blending an animation curves rotational offsets toward a target intensity and applying them each frame as a small rotation on the camera itself
Hi all, so I wrote some code using the Playables API, pretty simple stuff from the few YouTube videos about that.
mixerPlayable.SetInputWeight(0, 1f - weight);
mixerPlayable.SetInputWeight(1, weight);
clipPlayable.SetTime(0.0f);
playableGraph.Play();
❓ I am wondering, why is there such a noticeable pop / snap when changing animations, especially with the legs / feet?
Even if I keep the weight at 0, the character snaps back into place into the same Idle animation 🤷♂️
I tried going from Idle to the other animation in the Animator ("Make Transition") and it doesn't have this issue.
the snap back might be due to the root position of the animator
I tried turning off root motion as well. No luck
I read that this can happen if the skeletons don't match exactly,
But then why does the Animator not have this issue? Perhaps it does some extra stuff to prevent that 🤔
Getting Component from an Object in root
its just sprite, position offset, etc things that gives the rotating illusion when you change the direction of 2x4 table before placing for example.
Is this alot of scripts for a small game? Should I organize them into one more folder space?
You can organize them into folders like PlayerControllers , ui handler etc
well yeah, better more than having everything packed inside 1or 2 scripts.
yeah as it was recommended, you could group things and use folders
What i do is organize them using namespaces
oh ive used those before, but how does namespace work andhelp me?
I don't if my strategy is efficient or optimum but i do one global namespace like Project_Name{} and them use sub namespaces for work by creating sub namespaces that contain classes related to only UI stuff or Player Controls and their sub namespaces for divsions under those sub categories, and oganize files by namespace names like PlayerUtils, UI and then their sub namespace name folders, like Player Controllers, ButtonPressHandler{} etc
Usually what I do is organize the scripts in folders and the use those folder names as the name of the sub namespace
i do the same, usually create one global namespace like Project_Name{} and then use sub-namespaces for specific areas,
Ok this is my first project using unity and I don't know what on earth is going on. Basically, in my game there is two game modes that you can switch between, so I created a Scriptable Object class called GameData so that I could keep the save in between modes, so when I came to the problem of having to save the game to a json, I thought it would be relatively easy, by just saving what is in the GameData to the json then reassigning it once the game is started again, but for whatever reason, when I mention "data" (the actual GameData object) in any form rather than doing data.waveNum for example, it completely skews the data? I had this error before but managed to fix it by just not referencing the data at all in the code. It's very hard to explain so here's an unlisted YT video I made about it.
After recording this, once I took those two commands I put in back out, the data was still skewing so like I genuinely have no idea what's going on anymore, even chatGPT doesn't know what's happening. Ask me if you wanna see any scripts or parts of the code to help solve it I'll try reply as soon as I can. Please help me this is for my college coursework due in literally 2 days, thank you so much!
can any one tell me how can i create a good boss fight not about the move set about the coding
like give me a toturial or smth
i searched but i couldnt find smth good
@blissful stratus This is a code channel. If you want to talk game design create a thread in #💻┃unity-talk
no i want to know how can i code one
It is highly situational. This is not a place for a guided walkthrough. Search for a tutorial.
can anyone reccomend a tutorial for c#? all the ones im finding are useless
Check the pinned messages
thanks
how to use MCP?
How can I resolve a firewall issue in Unity Editor that's blocking external communications outside of my local IP address? The firewall only works if I compile at runtime.
Hello, I keep facing an issue every time I try to enter Playmode saying "All compiler errors have to be fixed before you can enter Playmode".
Any idea how to fix this?
You need to fix all compiler errors.
Check that you didn't hide error logs on console.
I went to the console, and the issue is blank?
Lemme screenshot it rq
Hide buttons top right on the console
My pc is struggling to open discord with 16 GB RAM so I just took a photo instead
blank error not bad
I'm using the same 16GB to open 7-8 firefox tabs, unity in playmode and vscode with spotify 😂
What's ur CPU, GPU and RAM speed?
I have one script trying to declare one public variable, I'm not kidding 😂
show code
Lenovo v15 g3, i712th gen IrisXe GPU 16GB 1200MT/s
Don't mind the sun hitting the screen
WHy is update commented?
I just said I can't open discord to send screenshots
It's full
but what does discord have to do with taking a screenshot though
How I'm supposed to send u a screenshot without discord
and how are you chatting with us without discord
Don't mind that too
Discord on phone
so you have an account
you can log in in the browser
you don't need to download anything extra
also while discord is a notorious resource hog, you should still be able to open it along side other programs with 16gb of ram
sounds to me like your cpu might be getting bottlenecked here not the ram
bro probably has a ton of background miners running
I have I5-12th gen
I kept checking for any apps running in background, nothing suspicious
visual studio taking 1G of RAM too
sounds normal
ngl I must go to 32GB
16Gb is huge i think there must be something else.
that would be right if I was using Linux
dont want to offtopic too much but maybe format your system
Might do it soon, but I need to back up alot of files
I feel so completely stupid but I cannot for the life of me figure out what is calling the Unity default example class method ShowExample() from the Create > UI Toolkit > Editor Window wizard resulting .cs file
What the heck is calling this method and why does it work when it doesnt appear to be a reserved Unity method (such as CreateGUI())?
Is it the MenuItem attribute that calls it as an entry point and afterwards the normal lifesyscle methods take their turn?
It's not clear what method you're referring to and where. Can you share the actual code?
(2D project) I'm trying to make a bullet that lowers health by 1 and then is destroyed on contact with the player but Unity is giving me an error saying the namespace for playerHealth couldn't be found.
The bullet is using
if (other.gameObject.tag == "Player"){
other.gameObject.GetComponent<playerHealth>().HealthUpdates(-bulletDamage);
Destroy(gameObject);
}
}```
playerHealth is on a script attached to the player as "private int playerHealth = 0;" with "playerHealth = playerMaxHealth;" at void Start
also both scripts are using System.Collections and System.Collections.Generic
the <> part takes a type, not a field
you need to put in the type of the component
playerHealth is not the component, it is a field of the component
Oh
the namespace for playerHealth couldn't be found.
that's also certainly not what the error is saying, try giving it a reread 😉
It works now! Thanks!
Is there a way to raycast to a specific face on an object? Also is there a way to see if 2 of an object's faces are connected via an edge?
for some reason new input system doesnt work for me
i linked this command to player input and to input action events, but still it doesnt work
the logs doesnt show up
have you set the input handling correctly, and how is your PlayerInput set up
is it just that action or are the other actions also not working
and event linker
all the actions
ok, you don't need both here
you either do this #💻┃code-beginner message or this #💻┃code-beginner message, not both - you're doing the work twice
i just added these lines since player input doesnt work
it's not going to make the player input work, it's just doing the same work again
have you set the input handling correctly
i dont know how i can do it correctly
im new to this
the game was using the old inputs
and i decided to migrate it to new one
you shouldve gotten a prompt to change the input backends
check project settings > player > input handling
to be clear, you aren't getting that "Jump" log, right
is this script on an active object in the scene
check the input debugger, to make sure your hardware input is being recieved
open the keyboard one and make sure it responds when you press buttons on your keyboard
specifically the button for jumping
you've set bindings for the inputactions, right?
yeah it does detect
have you done this
under the proper control scheme
wait
i guess the problem in the scene itself
when i go to the game, the menus and inputs cant be detected
extremely basic question but I'm trying to make a ball invert its linearvelocity vector2 in X when hitting a wall but keep its Y velocity but I am drawing a blank on how to do it
My guess was something like "rb.linearVelocity = new Vector2(? , ?) * speedf;"
this is in 2d yes?
* -1
only multiply the axis you want to reverse though
invert is just the opposite or reverse . . .
so whatever the value is, flip it . . .
the vector2 values are the rb.velocity.y and .x with one multiplied by -1
but yeah you were like 90% of the way there on your own
Thanks!
you probably don't want that * speedf at the end. the velocity already incorporates speed
idk what happened but unity just magically forgot what the onClick event is
the script was working before but then i renamed it to MenuHandler and now onClick won't show up
you probably have your own class called Button, notice how using UnityEngine.UI; is grayed out, that means the Button class you are using in this code is not from that namespace
i made a script called Button but i changed it to ButtonOverrides
but have you saved/compiled that change?
did you change the name of the script or the actual class name?
that too
changing the name of the file does nothing at all to the code inside the file. if you need to change the name of one of your own types then use the refactoring tools within your IDE to do it so that it can rename the file along with any references to that type
if you want to have your own, just place the class in a namespace . . .
well it's just a script for a tween animation when the mouse enters it
Nevermind, guys, I forgot physics materials exist, sorry for that 🤦
Hi guys does anyone know how to make a countdown timer? I have code provided and copy and pasted it into my script and added the counttext into the player controller but when I go to play the text says “count text” instead of the timer actually counting down from 60 seconds
: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 #🌱┃start-here
Most importantly the last few statements
you probably shouldnt blindly copy paste anything into your scripts without knowing how it works
😭 there were directions on where to copy and paste it tho so I followed that
probably is or a tutorial they miss followed
No it’s for an assignment but I figured it out it’s bc it told me to put the code after the void start and I thought that meant inside lol
actually, the method is just called Start, not void Start. void is the return type . . .
Does anyone know how to fix animations being stuck when I'm switching weapons? I have exit time off and I even set the bool to false.
Sounds like the animator controller might not be setup correctly.
You could add a line of code after switching that stops an animation. animator.Stop
Yeah Im not sure I just have a Default state and then that is plugged into the Reloading state and the reloading state is plugged back into default (and those gets triggered based on the bool value
I am trying to use the same damage script on a gun for both boss enemies and normal enemies, but because they use different scripts (for different attack reasons) I can't use get component to damage them, how would I fix this because I can't find a way to getcomponent for just a script in general
separate the health out to another component and/or use an event
just make a void then add the stuff you want in it and add the void in the events in the button
the issue was solved already but thank you
weird question but i am the only one who keeps forgetting how to make player movement
Don't add voids anywhere! You're gonna kill us all!!
It's not voids, it's methods. Void is a return type of a method.
it is called in c# voids so
no it isn't, dlich is right. they are methods. void is a return type for methods
nope
They're not. No one calls it that.
void means that the method does not return anything
so you forget too
i'm new to unity so yes
ok chill out all of you
i understand the logic behind player controllers but i forget exactly how to program them
me too
i was a godot user and i switched and godot way to do logic is easy so when i use unity by brain feels cooked
i came from roblox studio so i never had to program movement myself 😭
i find c# pretty simple though coming from typescript and lua
it's kinda just the engine itself i'm unfamiliar with
What is there to forget? Query the input, calculate movement vector, then use the CC movement methods or add force/set velocity of an rb.
And there are plenty of tutorials that cover that.
yea it's easy to translate that into unity scripts when you're experienced lmao
there are, it's about repetition though
not everyone immediately memorizes how to program it
For sure. But you remember the general concept as well as where to look in case you forget(documentation)
i do remember the concept
bro i came out of godot and i used c# for 2 years
i remember the concept too
It's not the same concept. It's a different engine with different implementation and api.
i know the concept of unity too
Which is why you need to watch a tutorial.
Or even better an organized course like those on Unity learn.
!learn
Over 750 hours of free live and on-demand learning content for all levels of experience!
you don't actually need to specify return types in godot. It's a dynamic typed language
gdscript or c#
well they said they used C#
why people start picking on people who used godot before like the engine made good games like buckshot roulette and baking bad
nobody is picking on you
k 
Not picking. Just correcting mistakes and misconceptions to help you grow.
ok
Are we still talking about how they shouldn’t be adding black holes into their project
wdym
Nope Im wrong nvm
Yes. Black holes(voids) don't contribute to your project in any way.
Also I forget how to make character controllers all the time (you brought this up earlier) it got demotivating tbh so I just have decided that whenever I make a new controller I am going to make a copy of that project and make keep it as a template
Highly recommend
Unless there is a better way to do that
git for cloud backing, and or a unitypackage you don't need to keep entire copy of a project for an asset
need help i dont know what happen but unity stop giving me error
it just pause without giving error . i tried to creating a nullreference error but nothing show
Perhaps console settings. Click the 3 dots at the top right corner and explore the console/log related settings.
Also make sure you don't have errors toggle off(buttons near the top right of the console as well)
yeah i know about that.
just deleted library folder and obj folder. it seem good now
I don't understand animations and my button got broken smh
i only wanted a fadeIn fadeOut animation
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
[SerializeField]
public Animator animator;
void Awake()
{
animator = GetComponent<Animator>();
}
public void GoToScene(string sceneName)
{
LoadLevel(sceneName);
}
public IEnumerator LoadLevel(string sceneName)
{
FadeIn();
yield return new WaitForSeconds(1.0f);
SceneManager.LoadScene(sceneName);
FadeOut();
}
public void FadeIn()
{
animator.ResetTrigger("End");
animator.SetTrigger("Start");
}
public void FadeOut()
{
animator.ResetTrigger("Start");
animator.SetTrigger("End");
}
}
You could just use an bool to do this instead and it would simplify the transitions too
Anyway we would need to see the transitions to judge whats wrong
but they work
it just that my BUTTON doesn't work
like i can't test it
the button itself is clickable but it does nothing somehow
but i set the function to it
you have not shared anything that mentions a button
GoToScene is set to the button
UGUI button?
what is UGUI
unity gui, the system that uses a canvas
anyway make sure nothing is blocking input to your button and double check your scene has an Event System
mhm
exposed value
public void ApplyMusicSettings()
{
string paramName = "Music"; // must match exactly
if (musicToggle)
{
mixer.SetFloat(paramName, 0f); // 0 dB
}
else
{
mixer.SetFloat(paramName, -80f); // mute
}
}```
same name
mixer has set
im so done man
why can't this editor change my exposed variable name to the same as i set it back then? smh
no wonder it can't find it
it was a AudioMixer issue
i didn't know when i expose something
i create a new varible
i just had to rename it to match my group name
smh
Do you know any other programming languages
I think its rather similar to java
yeah the syntax is rather similar to c#. I know python though ha.
how did you learn c# for unity?
Through panicking
oh dang
oh man good luck lol
Send help
that must be stresssful
😭 you've got this
I mean most of my AI is done i just need to do the player
This has been written in like 3 days
My current issue is detecting when the player places a new object the AI should detect if its in range and react accordingly
I hope the AI detection from my uni isnt great because im fairly sure half of this is chat gpt
My lecturer was useless
We werent taught this
Turns out you learn the language and how unity works fast when you’re panicking
LOL
cant u just shoot raycast at lightspeed, calculate time it took for it to come back, then using speed formula u can detect range
Okay youve lost me slightly
How exactly does that work
So the Zombies should detect the blue thing ans then stop
But the blue thing is placed during runtime
why not just use an overlapcircle ?
a circle (in this case) that detects colliders inside of it
you can filter by component, tag, layers. Up to you
Okay gimme 10 min ill attempt to code that
if i shoot light then
299,792,458 (lightspeed) divided by time it took to get to zombie
so i get
Speed = distance ÷ time or mathematically expressed as s = d/t.
like this?
the concept is basically similar, you would need to use the Physics2D. variant, that one is for 3D
sphere = 3D
circle = 2D
thats why I said circle not sphere
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics2D.OverlapCircle.html
is this better?

if you're gonna return a transform, that stageTarget assignment is kinda pointless btw
True
just return either hit.transform or null
Tank you
Its worked
Theyve stopped now to do the rest of it

btw if you call this frequently you can use
public static int OverlapCircle(Vector2 point, float radius, ContactFilter2D contactFilter, List<Collider2D> results); ```
version
depending how often it gets called x how many enemies
a filter by layer will also further optimize by not having to scan unnecessary colliders like the enemy itself, walls obstacles or whatever
Im not looking for efficent code XD
I just need it to work
If this wasnt due tomorrow i would code this better
I mean at max theres only going to be 11 objects on screen
My leturer never covered like half of this
Why am i paiying 9 grand for this degree if you dont teach me what i need to know man ;-;
Hey I was using ClientNetworkTransform in unity version 2022.3.9f1 with netcode for gameobjects 1.6.0 and it was working fine, but after updating to 2022.62f2 with netcode for gameobjects 1.12.0 it stopped working, when a server has ownership of the gameobject it moves fine on everyone's end but when the client has ownership it stops moving for all clients except the one that has ownership, does anyone know why?
ehh most degrees are just scam
you can learn this stuff on your own but somehow paper "proves" you learned the necessary material for some corporate job or whatev
Mood but need money
My degree is in robotics, I thought this would be a decent side quest
it was not
i should ask there?
yes, wouldn't hurt to also provide the code / setup you have that will help others help you
okie, thanks
newer versions of NetworkTransform now has a dropdown selector for Server / Owner based , idk about your version tho
i heard of that, but mine doesnt so :')
MY MAN
I just need to pass man send me luck
good luck
i have the same issue
i wanted too much on my project
When is yours due
Oooof
Mines tomorrow at 1pm
Any ideas why
This works
Oh never mind
I never call the other function
XD
hmm yes we all understood what you meant /s
you know when youre confused why it doesnt work and you start to type and then you realize
Ooops
XD
Never called the function
many people here fail to even realise that so you are doing good 👍
We are getting there, Only 5 more thing to implement then my write up ;-;
This has been a painful couple of days
i'm trying to make a variable for a ui panel element but it only comes up as a debug element?
nvm the panel is an image type i guess
If its ugui then yes the component used for sprite rendering is Image
Trying to get a sprite to follow the mouse where have i gone wrong
yes i know this is a mess
Never mind forgot to save the file
IT works
XD
you can use the new input system to just get the cursor position
oh nvm
When you code for too long easy mistakes come frequestly
How am I supposed to make an animation that just goes up and down, I need it for a boss I am working on where he jumps into the air and when he slams down it spawns a spike, but when the animation plays he goes to 0, 0
Without codes, we can’t be sure. First, u can check if the animation is using root motion
I tryed to change it a bunch and am now just confused lol
also for refrence the boss is lit just a capsule
Good evening, I'm having a problem with Unity. This error code appears when I launch a project: "Code execution cannot continue because Unity.dll failed to load. Make sure you meet the system requirements for Unity."
I've tried uninstalling the Unity vrctimes and Unity Hub, restarting, and reinstalling, but the problem persists.
Thanks in advance.
You need just change this setting
By animator component
on or off
On
No
is that the issue
ok
yeah that didnt fix anything
do you think it could be an issue with it being navmesh
I figured it out
not entirely sure if this is considered beginner, but I'm not seeing anywhere else that would be more suitable for this
in my game, I have a mode where players have to say a word from a category, I have a lot of predefined categories and words that work for them, but I also want to allow users to use their own categories in private rooms, unfortunately, having them define their own dictionary of words sounds very very unfun and kind of kills the idea of allowing user defined categories, my initial thought to get around this was ai, and while that works, I would like to avoid it if possible, but I can't think of an elegant way of doing it that doesn't result in a lot of bruteforcing or tons and tons of extra work to implement, anyone have any ideas on this?
I also need to actually have a system for "valid" answers, since this will be an online game and it does need to actually validate the answers, plus that way there aren't arguments over if a word works or not
so you want a mechanic where people can create custom categories to use in private rooms but you think creating said catergories will be unfun?
the game is essentially "say a word from the english dictionary that falls under the category"
so unless typing in hundreds and hundreds of words is fun
yeah, it'd be unfun to manually make the list of words lol
so the "creating a category" portion is mainly just choosing something that would be fun
like, unity, if you wanna play with a bunch of game dev friends
this is a more of a design question
and less of a code one
try making a thread in #💻┃unity-talk you might get better answers
hmm I guess
I just need to figure out what method to implement something like that would be solid, to get that list of valid words
This would be easier if they were given multiple choice with the correct word and incorrect words. There are always more than one word that fits, so allowing them to enter their own will add difficulty in creating the system . . .
yeah, but unfortunately it's not supposed to be a quiz game, but more of a memory and endurance game
seeing how many you can think of and saying it before your time is up
and like, as I mentioned, Ai would work as a sort of "is this a valid word for category?" and then having it respond with Y/n, but that sounds overengineered and a very wasteful when it comes to resources, and it would also slow things down a lot
Can I send my game to someone to help me fix a bug with it?
the entire game? 