#💻┃code-beginner
1 messages · Page 299 of 1
does anyone know wtf a float y is?
you're trying to create a tuple there. that isn't how you create an instance of Vector3
How do I change it to be a vector 3?
take a look at the docs to see how you create an instance of a Vector3 https://docs.unity3d.com/ScriptReference/Vector3-ctor.html
ooooh my god I forgot to write new vector 3 I'm an idiot
I'm actually confused why it says (float, float y, float) there instead of just (float, float, float)
I clicked Box collider beacuse my character kept falling thru the map and then I pressed play and it just said this and it's not loading and i'm worried if it didnt auto save please help me. (By the way I was waching a tutorial on how to fix it and it said to do that and no its just stuck loading)
yeah that is a little weird, but i wonder if maybe the compiler is inferring the name from the name of the property used?
I guess? Weird behavior
!bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
yeah so i tried everything and its still giving the error
oh neat, it looks like that is exactly what it is doing
all of your packages are up to date?
AUUUUGH I lost half of my work cause a stupid Unity bug.
remember to save often
You can recover a scene as long as you do it before you re-open
https://blog.theknightsofunity.com/can-restore-unsaved-scene-unity-crash/
And this sounds more like an infinite loop in your code than a unity bug
Is there a built-in solution to cursor.locked not interacting with UI? I have an FPS character and want it to interact with some world space canvases.
all of it should be up to date let me check
you should have already checked considering that was literally the first step i said to take
No I turned on Box colliders and pressed play and it just didn't load so I had to force close it with task manager because It wouldn't let me close it from the program
The common fix here is to use a custom input module
https://forum.unity.com/threads/cursor-cant-click-in-locked-mouse-state.1171457/
https://gist.github.com/EmmaEwert/fad38a248f62e1c7267daa4e778468b1
If it freezes when you hit play, it's almost always because of an infinite loop
ok
great thanks!
Theres no temp folder in the project folder
Depending on what version of unity you are using there might be a different name, look for something named along the lines of _Backupscenes
I couldn't find anything called _Backupscenes
Are you checking this before re-opening the project
I opened it like 2 minutes ago then I closed it and im looking for the Backupscenes now
So you did open it
meaning it's cleared out the backup scenes
yes after it crashed I opened
you have to do it before reopening
😭
Nooooo
Next time I will do ctrl s before playing
or do it from time to time
Ey, I am planning on adding a "scatter shot effect" along side the main bullet as a powerUp with a variable amount of pellets based on how many copies of the powerUp does it have. And I am wondering... should the logic of how this projectile works be in a prefab that spawns all the pellets or be in the overall method that I use for the player to spawn projectiles. What does make more sense?
By the way Im not good with Unity I started using it yesterday but not gonna lie its a bit easy to learn the basics
Cause I am kinda not sure what to do here, since I am kinda considering this "burst of projectiles" as its own type of projectile, so seems like should have its own prefab, but it also pretty much just add smaller copies of the main bullet with a small random angle offset
yeah i did check but i just wanted to check again and yes its all up-to-date
hello?
Did you delete your library folder as directed?
yes
And when you reopened unity, you got a loading bar that took a while, as the library folder regenerated?
yes
hi y'all.
i want this train object (which has a trigger boxcollider) to call a shake() method on all the tree prefabs i have around the scene, but for some reason it only recognizes the player and grabbable prefabs. i have no clue why, this is what my tree prefab looks like (it has a box collider), i tried messing with the settings on that but i'm stuck. anyone know why the train wont print the tree objects
Looks like the animator, the script, the collider were added on a prefab instance, but not applied to the actual prefab. As shown by the blue margins on the left of the Inspector
(the collider is also not a trigger collider here)
i see
but whenever i update the values in this tree prefab, it does update all the other instances on the scene
even when i enable the trigger collider option for the prefab (which reflects on all the instances in the scene), it still doesn't work
here's the code, but the part i care about is just the print line, but since its not printing any of the trees, im assuming theres an issue with the colliders somehow
First things first, apply the changes to the original prefab anyway, using the "Overrides" dropdown at the top of the Inspector, and try again
And for OnTriggerEnter to happen, one of the two objects must have a trigger collider, not the other, and at least one needs a Rigidbody.
Also make sure you're moving the objects in a way that uses the physics engine, by interacting with the Rigidbody for example. Directly modifying the Transform does not use the physics engine.
Ohhh i see
Physics troubleshooting guide if needed
Wow you might legitimately be the first person I've seen actually follow that link and go through the follow-up questions it asks to find the solution to your problem
Most people just say "that's too hard I hate reading" and demand we solve it for em
works! tysm
hi, im having dificulties understanding how to acess a script in my game, im working on a enemy ai that uses a StateMachine, the enemy object uses a script for its ai that calls other scripts that are its states, being a patrolState and a attackState, im having dificulties in the attackState script being called, the way its supposed to work is by a canSeePlayer method that uses a ray to detect a player, i have run various debugs log, and it should work since it has all the requirements for the attackState to be called, but i dont really know what to do
is it possible to remove a specific item from an array or is a list needed
Guys I'm making a Gorilla tag fangame in Unity and whenever I press play the thing falls thru the map and it doesent stay on the ground. Please help
did you add a box collider to the ground?
I don't know how to do that so I don't know
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Arrays have a fixed size so elements cannot be "added" or "removed". Prefer a List<T> if you're planning on adding or removing elements. Keeping the array and setting the unused elements to null could also be an option, albeit less practical than using a list for this specific case.
alright thanks
select the object and on the inspector add a component and go to physics
ok
What do I click on physics?
which one?
What component are you trying to add
box collider and scale it to match the floor
Do both things have colliders
Does your player have a collider
No
Showing the inspector of both objects might help
So uh
I'm not sure about how you set things up
But basically
I think you should put a collider on literally everything that shouldn't go through things
And everything that shouldn't allow things through
I pasted in the map from my last attempt because I got something wrong with Photon last time
I have no idea I started using Unity yesterday
Ah i see
I do know most of the basics
the ouside face is where you statnd
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Creating a project involving VR as your very first is pretty much an extremely bad idea
Same thing goes for multiplayer
(Your VR setup is throwing some errors by the way)
how?
Well read the error message and you'll se why that is
I following this https://www.youtube.com/watch?v=KBcsX0uCNi4&t=1062s
Unity Hub: https://unity3d.com/get-unity/download
Gorilla Locomotion: https://github.com/Another-Axiom/GorillaLocomotion
Photon PUN 2: https://assetstore.unity.com/packages/tools/network/pun-2-free-119922
Photon Voice 2: https://assetstore.unity.com/packages/tools/audio/photon-voice-2-130518
Photon Website: https://www.photonengine.com/
Pho...
Yep. Multiplayer + VR. The combo of death
Your VR package is deprecated as per the error:
XRRig has been deprecated. Use the XROrigin component instead.
Soo how do I fix that?
I strongly suggest you follow a basic introductory tutorial to Unity first
do something simple first like this https://youtu.be/XtQMytORBmM?si=wkUnLm5YnZG5h6q5
🔴 Get bonus content by supporting Game Maker’s Toolkit - https://gamemakerstoolkit.com/support/ 🔴
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then gi...
hi, im having dificulties understanding how to acess a script in my game, im working on a enemy ai that uses a StateMachine, the enemy object uses a script for its ai that calls other scripts that are its states, being a patrolState and a attackState, im having dificulties in the attackState script being called, the way its supposed to work is by a canSeePlayer method that uses a ray to detect a player, i have run various debugs log, and it should work since it has all the requirements for the attackState to be called, but i dont really know what to do
Well if im gonna make a new project ima save my map with the FBX tool thing that lets you export objects you made in Unity
this is like the worst way to send code
how should i send code better?
i am 100% sure you've been told how to here before
dating back to january #💻┃code-beginner message
... if anyone knows
which ui image
oh my bad i though you meant because the code sucks, ill do that
in the video which shows the white image there (that one was for when there's 2 players
Well the fact you have a class called Enemy_1 is a bit worrying haha
what do you actually want im confused - for it to cover the whole screen?
Also, try to cache those GetComponent calls
Might wanna use an enum instead of using reflection too
Now, for the real issue, I am a bit confused. What is the actual problem. And what do the debug logs say?
yeah, (that ui image is taged transition1. if there's two players the ui iamge should be like that, but if there's just single player and the ui image should rezise the width)
can you track the amount of players anywhere?
because that could help
yeah, (Player 1 is tagged "Player" and Player 2 is tagged "Player 2", it is also shown in the script.
try messing around with the rectTransform of the ui image, something like this i think im not too sure though i dont deal with UI that often
image.rectTransform.sizeDelta = new Vector2(width, height);
erm
Do you HAVE a variable called image?
Or width or height?
Because you would obviously need to make those....
Does vector3.normalized go from -1 to 1 or just 0 to 1?
0 to 1
ok thanks
-1 magnitude is not a thing
wait but like if the vector 3 had negatives would they stay as negatives?
Well, the magnitude is the length, which is only positive. The components in the vector can be negative
Sorry if I misunderstood you
Oh ok, gotcha.
nope
Welll... then yeah that code will obviously not work.
That was an example, not something you can copy and paste
because since the ui buttons is supposed to be like connected to that script when you click on which how many players
I'm not really sure how that relates to what I said. But ok
Make the variables you need so that it isn't a basic compiler error
hi heres are the scripts https://paste.myst.rs/30lnmln8
a powerful website for storing and sharing text and code snippets. completely free and open source.
What is image? What are width and height?
image (UIimage) width and height (recttransform)
Okay, and where are those variables defined?
Are you sure?
I just guessed and think
In this script, what are image, width, and height? Where do you define those variables?
I thought under where the camera also define (changing width if it's just one player)
Okay, so, you have a variable named uiImage, and a compile error
Ok so this may be a little hard to explain but could anyone give any light into what's not working here?
The End of the blue line is supposed to be facing in the direction of the red line with the length of the green line, since the green line and the blue line are supposed to be on the perimeter of the same circle around the object in the middle. r is the distance from the center object to the end of the green line, so it should be the radius. The thing in the center is the "origin" and the thing at the end of the red line is the object running the script so it's where the transform is coming from. I've been trying to get this to work for hours now.
yeah and no, I just wrote the one below
And I have absolutely zero idea what the second image is supposed to convey
This doesn't seem to have anything to do with what I asked
changing the camera width size, and I said the image rezise should also varieble along with that
Yeah, so, you're changing the camera's rect, but I don't know what that has to do with my question?
Oh come on.
private width ?
You have a line that's trying to use image, width, and height. What are those
aren't width and ehight also supposed to be there?
where?
You have been using c# for quite a while now. You should absolutely know this by now
like what i wrote with private Image uiImage
I am completely lost as to what you're talking about. private Image uiImage is a variable declaration. But I have no idea what that has to do with what we're talking about?
I know that, but I never used that part with having width and height resize uiimage in a script before
are height and width also supposed to be variable?
Irrelevant. You are making a number. How do you make a number variable?
This is likely the ABSOLUTE first thing you ever learned in programming
I do not know what you are asking. What are you actually trying to do
Your explanations aren't making sense so let's back up. What is the goal you're actually trying to achieve
i need a method which is called when the object is created
Awake breaks other things
Start
OnEnable
Awake
Then fix the other things
what I'm trying to do is that with player 1's transition is that it would change the UIImage's width size to cover the whole screen if there's just player 1 there
Okay, so you're trying to set the width and height of a UI Image
Which UI Image are you trying to set
how can i fix this
i have an instance of my EquipmentManager
What about it
the instance is set after the other awake
Awake for self-reference
Start for external references
Can I like... intentionally skip the Start() method of a instantiated object?
what do you mean
No, Start runs on every object
yeah i know
but what im saying is that start isnt called when an object is created
For things that are on this object, use Awake. If you need to reference something else, then use Start
Yes it is
Is the object disabled?
yes
Then it will run start when it's enabled
and the reason why the uiimage is that different width size is because it's for when there's 2 players
i need it to run anyways
So, which UI Image are you trying to set
Sounds like an xy problem
this image
Could you just run your own "start" method in these cases?
Okay, so you need your script to get a reference to this image. That's the first step.
"how do i do that"
yeah, and the tagname
Wait what's this about a tagname
what does that have to do with anything
I kinda want to not set the projectileData to the playerController, but instead set it manually, in an instance but I need that reference at start
...what
Cause I want like spawn several bullets that are slightly modified
why are we talking about projectile data
when did the conversation become about projectiles
Wait, nevermind, I thought you were linedol
I'm confusing myself here
Is the value that I want to be setted on the start of the new instance
Don't really know how to work around that
because in the script, it have the tagnames so the other scenes can tell when i click on the player button, and since Main camera for player 1 also have a tagname
Then this either shouldn't be in Start or you should spawn a different object that doesn't have this
Okay, and what does this have to do with what we were just talking about
I asked you to reference an image
why are we talking about tags
because that image have the tagname "Transition1" so I just wanted that the it's referencing the right image it's supposed to reference
Okay, so, why are you doing anything with tags. Just drag the reference in
the playermanager script is in a different scene, how can I drag the reference in that is in another scene?
@hushed hinge your width could be modified by transform.localScale.x it's not like per-se modification of width, but you can kinda stretch the image. what's best about it, you don't have to assign the width anywhere. Just assign that image. Which I guess you now have problem with since your variable is private and you can't assign that image in the inspector. Easy solution: [SerializeField] private Image uiImage; and then it's assignable thru inspector.
I am not sure if that's what you are looking for
Okay, that was context I didn't have. Sure, use find to get it across scenes. Just have a variable that holds a reference to the image you want to change.
You shouldn't modify the scale of a UI object. You should make changes to it through it's rect properties
Having inconsistent scales will completely bork your anchoring
Couldn't spawner of that object set the projectile data to what it wants?
now without any jokes: how does one modify the width thru rect property? I am also a beginner and I am legitemately interested since I don't know it
sizedelta
thank you
Yes, but it is kinda weird, cause I am treating it as sorta of a shot modifier, so instead of being its own shot is kinda like an extension of the original one...
sizedelta is Vector2 so basically 2 floats representing X and Y?
Probably should't do that, but I am really struggling to trying to wrap my head about how I want to actually code this
ok
welp, ive just learned the hard way to use fixed update for velocity based movement
my player was rubberbanding like a game of pong
width and height you mean yea
Swapping to a different prefab would be another option if you don't want the user to be aware of that detail
Okay, now get the image component of it and store it in a variable
yeah, width and height, correct. Thank you. So basically like this, right?
ok, almost there
That isn't you storing that image component in a variable.
Can I not have an struct parameter as null?
Is there something equivalent or is just not supported?
do you mean store it in inspector? (and what do you mean by I'm not storing that image component in a variable? I did the same thing with the mainCamera)
No I mean store it in a variable
You need an =
but you told me to get the image component of it
And store it
Getting it and throwing it away isn't great
how come "Image change" only gets printed once at 16 seconds? Shouldn't the modulus operator usage here usually make it print at 16, 12, 8, and 4 seconds?
And store it in a variable.
Delta time is in seconds, so I'm not sure what you're calculating there🤔
alright, removed the % 60
Does it work now?
how do I do that? (I have been searching)
With =
prints out once at 16 seconds, but then doesn't for the rest of the time
Share the new code
oh,
What
using UnityEngine;
using UnityEngine.SceneManagement;
public class Cutscene : MonoBehaviour
{
public float targetTime = 20.0f;
private void Update()
{
targetTime -= Time.deltaTime;
int second = (int)targetTime;
print("time: " + second);
if (second % 4 == 0)
{
print("Image change");
}
if (targetTime <= 0.0f)
{
TimerEnded();
}
}
private void TimerEnded()
{
SceneManager.LoadScene(2);
}
}
Surely you've set a variable at some point by now.
hi guys i have a problem
And it only prints image change once?
yep, no clue why
could it be a float/int conversion thing
Take a screenshot of your console when it's about to reach 0
No. I don't see any problem in the code actually
can i get sameon to strem my project to ??
oh, then I should use Int?
Is a UI Image an integer
i have a problem in animation and i dont know howe to slove it
right before it reaches zero & the only time it prints
is it code related?
- This is not a channel related to animation.
- You can record a video.
You have collapse enabled in the console
Disable it
hmm... I don't think so?
is there an effecient way to tell code to run only once when its something that u have to run in update? usually i just create a new bool for just that where the bool starts off as true, and if true, the code runs the thing i only need to be run once then sets the bool to false
Okay, congratulations you've made a variable. Now store your reference in it
i dont know if the problem from the cod or from the unity
If you mean when there's a change? You can learn about events. Otherwise, if it's something that has to while something has a specific value, then Update is correct.
but it's still red underline
Because that makes no goddamn sense. Please read the link I sent and learn how to set a variable
no in my update logic i just have to for example set the speed to 0 (only once) when a specific if statement runs for the first time
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour
{
Animator anim;
Rigidbody rb; // Declare a Rigidbody variable
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody>(); // Get the Rigidbody component
}
// Update is called once per frame
void Update()
{
// Check if the Rigidbody component exists
if (rb != null)
{
// Access the velocity only if the Rigidbody component exists
anim.SetFloat("Speed", rb.velocity.x);
}
Debug.Log("Speed: " + anim.GetFloat("Speed"));
}
}`
like here, in the else if (hasBeenBlocked)
I want it to set speed to 0 once, then start doing this new movement it does if the object has been blocked
you have to start by explaining the actual problem..
Why would you think the = sign goes on the right of that?
As digi said
Surely you've set a variable at some point by now.
I think they would benefit if you describe your problem
Is there an actual issue with how you have it? Are you just asking if it's a bad performance thing?
I did
bad performance thing
It's fine
i just dont like creating a new bool if it has 1 small use
So why have you typed whatever the hell you typed
It will have zero affect in your performance
If you made about four trillion of them your games build size would increase by one kb
Well, that's not a performance thing, that's an architectural thing.
I add animation "ideal" and it works but to add more animation I add this script in the controller but it doesn't play
yea sorry i meant that
And, sure, you could clean it up with work. Character Controllers are difficult to keep looking nice, it takes experience to know how to properly break it apart.
In the end, as long as it works. 🤷♂️
is it recttransform I'm supposed to type, right?
For starters you could separate update into several methods. Then you could use the state machine pattern to switch between logic depending on the state.
hmmm alright, was just wondering if someone had foudn a more clever way
No. You are supposed to store the image you want to reference in a variable
reading the error message should give you the info you need
alright
update in phases and use a state machine is typically the best you can do if you are looking for a "generic" way to do it cleaner/better
a.. state machine pattern ?
holy crap it's printing a gazillion times LOL
I was wondering what that number in the hundreds was next to each message and assumed it was the amount of frames between each second ig those were the amount of messages haha
but it's right here
I gave it to chat-gpt to give me a slove but they don't give me any solution
i think Image
is a UI thing
you mgiht be thinking of Sprite ?
it is an UI
You have created a variable. Now you need to set it to the image you want it to hold
Did you try giving it to a search engine instead of a text generator?
i dont undrestand the problem
i l'll do it now
Chatgpt misses a lot of small details and what not, it just doesnt think like a human, i suggest you watch a tutorial about basic unity functions, perhaps in a language you are used with.
Anyways, show the heirchy of your "Ch38_Shirt" object
it's right there
#💻┃code-beginner message
Ask yourself this
This question is the answer to that error
Do you know what a variable is
A programming pattern
Sorry i meant inspector, can you show what components you have?
then I don't know what to write there besides rectTransform?
That is not the issue....
At all
The issue is where you put the = sign
why do you think it goes on the right?
instead of the left
Well, I guess you are trying to assign the IMAGE to something (so I guess the rectTransform is part of the issue)
Okay, let's pretend you want to store the value 3 in an integer variable named x. How would you do that
how do I get "image change" to print only once at exactly multiples of 4? Here's what I tried
targetTime -= Time.deltaTime;
int second = (int)targetTime % 60;
print("time: " + second);
if (second % 4 == 0)
{
for (int j = 0; j < 1; j++)
{
print("Image change");
}
}
hmmm....
int x
x = 3
Perfect. Great. You understand the concept
Oh man you're almost there you're red hot
you are trying to assign the IMAGE to something (so I guess the rectTransform is part of the issue)
Just a little bit more, transition1 is an Image, so you have to store an Image in it. Now, how would you get an Image Component from an object
GetComponent?
🎉🎉🎉🎉🥳🥳🥳🥳 🎉🎉🎉🎉💯 💯
Now just... remember this for next time?
ok
Now
you have a variable
that holds a reference to the Image component on the object tagged "Transition1"
This took like two hours so I honestly do not remember what you were trying to do with it
oh my god, yeah, ok, now I need to figure out with changing the image width size
There are multiple ways. Easiest is to change the sizeDelta (this is the width and height variables you see in the inspector)
https://docs.unity3d.com/ScriptReference/RectTransform-sizeDelta.html
So... yeah there is no animator attached to this object
Wasn't that the error?
like this?
Sure. Make those numbers variables though
but i add to the idel
Correct. This will set the width and height of the transition1 object to 1280x720
It is looking on the shirt, so it doesn't matter if it's on Idle
so add animator to all the object on player
No. Fix the code
To find the animator in the right place
Why is PlayerController on the shirt in the first place?
Yes. GetComponent gets the component ONLY from the object this script is attached to
I think this is an important question:
Why is PlayerController on the shirt in the first place?
what i changet to
i dont know
i can change it ?
Then don't have it there
ah you talk about the script
bro, i searched for 1 week and the problem is PlayerController on the shirt
it solved but i want something more
ok, it actually works
even though if it works?
Always make variables instead of magic numbers
If they're variables you can easily change those numbers from the inspector without having to recompile
like that?
i think this chat is not for animation
Well, speed seems to be 0
And you only set it when Rigidbody is not null
So, I think perhaps there is no rigidbody on that object?
i can solved with the code or in the engin
Do you need to ask?
Depends on the issue. Do you have a rigidbody on the object?
So no
You have a CharacterController, which is incompatible with a rigidbody
Your Mouvement component has a speed, use that instead
but then the transition 1 won't be visible
What? I don't have any clue what you are saying
Ah wait. Tell me you didn't forget to assign the variables....
The int and float types default to 0, so if you forgot, then you are assigning 0 to width and height
i add a regidbody
so what next
Nope
You literally responded to the message where I said you cannot do that
Bad. Remove it
ok
You have a CharacterController, which is incompatible with a rigidbody
Your Mouvement component has a speed, use that instead
this?
Do you not see those red lines
This is the most absolutely basic thing you need to know how to do
https://www.w3schools.com/cs/cs_variables.php I read it here
That is assuming you are in Main
Which you are not. You are in a class
Just assign it in the initializer or via the inspector
Or in Start/awake
use in cod or in unity
In your code
I did do tht before when I asked
That is assigning the SizeDelta field btw
Not your x and y variables
So yeah, those would still be 0
Show your code
What is Mouvement
What about the intellisense?
where i can get it
Where can you get what? It's YOUR script
everything works
uhh could i get a bit of help with having my code play audio?
im trying to have a thing where when in this case the laser hits the enemy, it makes a sound along with the animation i have for an explosion, as well as removing the laser and enemy
i've tried to implement things from tutorials i've seen, but i kept getting a "cannot play a disabled audio" error, and looking through people saying the same thing none of the solutions for them worked for me?
this is the code as it is before trying to add audio, i followed a tutorial that i thought would work, with playing an audio clip when a collision happens, but i think it's due to the laser being destroyed when it hits an enemy, and so it isnt able to make the audio? i'm not entirely sure i'm new to unity, so a lot of what i get is from tutorials so im not the best at figuring out whats wrong with it
Yo, Im following unity's official tutorials like someone recommended here, at first the quality looked amazing, but theyre kinda overexplaining the most basic things Ive already discovered on youtube, anyway heres a physics related problem I got, so why does this wooden obstacle always back down in place like this instead of being kicked forward like a soccer ball after the truck hits it? It's supposed to go side ways not say in one place and return to its original position right? wtf
i fixz the prroblem in unity
but i have a probelm
the code does do anithing
Did you assign mouvement?
yes
Ah yeah, I see the getComponent call
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour
{
Animator anim;
float curSpeedX;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
// Access the curSpeedX variable directly
anim.SetFloat("Speed", curSpeedX);
Debug.Log("Speed: " + curSpeedX);
}
}
Oh. Ok, so you just got rid of the mouvement reference
So this will basically do nothing except set the speed one time
so how i can fix it
Unless you set curSpeedX externally
hmmm how i can do that
in unity or in the cod
Go back to referencing mouvement and use that speed 🤷♂️
ok
Ah, I see you tried that in the video...
this is the full script, just not sure if there's a way i could add a way for it to play an audio clip each time the laser prefab (which is what the script is put onto) collides with an enemy
i think if i could figure out a way for this to work, then i could make it work for the other parts where i need audio to play, i'm just not sure how to go about it
Assets\playerController.cs(24,45): error CS1061: 'mouvement' does not contain a definition for 'speed' and no accessible extension method 'speed' accepting a first argument of type 'mouvement' could be found (are you missing a using directive or an assembly reference?)
replace the referencing mouvement by Speed
that what you say right ?
Again, this is your script, so you should know what to change speed to.
You had different variables for it
You had walkSpeed and runSpeed if I remember correctly
i wille change speed with all the variable for see the problem
i can do some math and add the rune speed and walk speed in a new variable named speed ?
Sure. You probably want to do a currentSpeed variable, and just switch between the two
finally!! the cod work
Are any of the constraints enabled?
what are constraints??
nope
but it looks like something like the box is hitting into something like an invisible wall
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(transform.forward * Time.deltaTime * 20);
}
}
this is my script by the way
could it in any way be related to this method that im using?
i changed it to ```c#
void Update()
{
transform.Translate(Vector3.forward * Time.deltaTime * 20);
}
Vector3
Why doesn't it go forward?
Vector3.forward will move forward on the world z-axis . . .
Ohhhh, you're using Translate?
You should be using rigidbody motion if you have a rigidbody. Is this what the tutorial suggested?
That tutorial is garbage
It tells you to use translate and shows physics interactions
It's not their fault
It's a bad tutorial
nope
I ended up just... checking for one of the values inside the struct to see if it was 0 (aka not setted), that would mean the struct is not set yet. So I just check for that before setting it to the playerController.playerProjectileData. That way I can set it when instantiating a new projectile and will skip this step enterely. Just is someone ever want to know about that, which I doubt, but there it is. I just answered my own question
isnt it supposed to go wherever the car is kicking it towards?
no, that's what transform.forward does . . .
thats what the car does
the box has no transform.forward
it has a rigid body and a mesh collider
and so does the car
have these components
Yeah, that's what I was thinking
Pretty sure I did that tutorial and found no issues whatsoever. What's going wrong?
huh? every GameObject has a Transform component. so it does have a transform.forward, which moves the GameObject along its local z-axis . . .
which object for what? i was merely answering your question . . .
you didnt answer my question at all lol
my question is why do the boxes stay in place
instead of being shot forward
I just finished the tutorial where he explains the truck script
but he doesnt explain why my obstacles just stay in place
his seem to work differently
and i did exactly the same steps he followed
the boxes will shoot forward if a strong enough force pushes it . . .
That's just how physics work, make it go faster or the box has less mass if you want them to gain more force on collision
i don't tinker with mass. are you using velocity or force to move the truck?
You can also change the physic material of the boxes, you might like to add some bounciness there
Translate moves the object in that direction that much amount each frame, but it doesn't apply any physics, it is just basically changing It position constantly, making it have no force whatsoever on the the boxes, they are just being gently pushed away by the colliders and rigidbodies, but there is no velocity
Transform.Translate is the same as transform.position +=
no physics are used
it's just a rigid "go here to there"
tutorial is bad if it's telling you to transform.translate for physics
Translate doesn’t use physics
you can use rigidbody.moveposition
Why tf would the tutorial say that
Overview: In this lesson you will make your driving simulator come alive. First you will write your very first lines of code in C#, changing the vehicle’s position and allowing it to move forward. Next you will add physics components to your objects, allowing them to collide with one another. Lastly, you will learn how to duplicate objects in t...
its literally on Unity's official course itself

this is so sad
yeah you never want to do that because transform.translate sets the position directly without consideration for physics
you can try to set the collision mode on the colliders to continuous and see if that helps
or lower the speed of the truck
I know, I did that too. It is not bad, you don't really need to know about adding forces yet, they are just showing you can move stuff in scene and that they can collide with each other, that's all
is it possible to use unity to decompile a game
i don't think you decompile a game with unity
you can decompile a game and then open it in unity
but unity itself doesn't decompile
ok
oh ok, so its not supposed to move around of its place? weird
hopefully that wont cause problems as i continue on with the tutorial forward right?
is there a way to decompile a game
yes
but the ethics are questionable on that
wdym
we don't discuss decompilation of games on this server. you'll have to go elsewhere . . .
They do collide, they are just not having any forces taken into account for that. It is just trying to prevent two different rb colliders to exists at the same point, which is not the intended purpose, but does work just fine for the tutorial
Just don't that your own, you are not supposed to
imagine you spend time making an entire game
for some random dude on the internet to open it up
and see exactly how everything that you worked for works
to get access to all the assets, all the code, etc
i was just trying to make a mod for game so it can add multiplayer
is there any way I can temporarily fix this at least? lol
ehhh still pretty questionable. either way, no decompilation talk here
ok
im still not entirely sure with this, if somebody could help me out i'd appreciate it, it's the main problem im having right now (though i expected it to be the easier thing to do)
but i followed the tutorial, and this is my code, just adding an AudioSource and having it play,
but i think it's not wanting to work because the script is on a prefab, meaning i guess when its trying to play the sound its also having the prefab be deleted, so i'm not sure how to go about implementing a way to have it play the sound even if the prefab is destroyed?
transform.translate would have to be replaced
Modding isn't really an allowed topic on this server. Besides, modding is very specific to each game. You should look for a modding community. Preferably one that is related to that game as well.
his seem to work perfect although he said somewhere in a random moment in the tutorial " im just switching to an ANCIENT version of unity right now" because reasons 😄
ok I didn't know.
sorry
What do you even want to fix? Your physics don't need to be exactly the ones shown in the tutorial, just move on with the lessons, you will learn so much more than by getting fixated on this tiny issue
do the official unity tutorials work? idk i don't think i've ever watched like a tutorial to learn a game engine or new framework that really worked
i just mess around and when i don't know how to do something i look it up
and then i learned how to do it
What's the issue exactly?
your best bet is to get in touch with the makers of that game to see if or how you can mod it . . .
ok I'll make sure to try that
i don't want to post my question to multiple channels but general is getting no activity 😭
Usually you either place the soundclip on something else or "fake destroy" the object dissabling any colliders and renderers but let it stay there for a few seconds to play the clip. Or you can just spawn an empty prefab that plays the sound clip and is then destroyed.
how would i go about fake destroying this?
with another sound idea i want to implement this would work since i can just have the player play the sound
but with this one both of the objects involved are prefabs, and both get destroyed, so i'm not sure how to implement it
Your wall of text is hard to read. Maybe make it clear where a short description of the issue is(like an error or unintended behavior) and where the context is, because a lot of your message is about the project itself, rather than the issue. Since it's hard to read, most people would just skip it.
What do you want to destroy exactly?
I like how people swear by Unity's official tutorials, i just started it yesterday and I remember somewhere in a video where he spent like a whole 6 minute straight explaining how ctrl+z works to undo stuff as if it's advanced thermodynamics
in the game, the player shoots a laser, which is what this code is for, and so when the laser collides with an enemy, it plays an animation and destroys both the laser and the enemy
im hoping to have it play a sound around that time, which is why i wouldnt mind just making the laser still exist, just not be visible and not collide with anything for a few seconds
ty for the tip! I just figured it out, but i'll keep it in mind for the future
I literally just watched everything in the course at x2 speed and still seemed slow
im just not sure how to implement that, i'm kind of new to unity, i just started it for this semester, and i havent gotten a good grasp on it i feel like
Get the collider and the mesh renderer of the laser. Then set enabled to false. Add a delay to the destroy method to let time to play the sound
You could instantiate a new object with the sound that also auto destroys itself after x amount of time, that's usually what I end up doing for "on destroy" sound effects
Just do whatever works for you now until you feel confortable to do a bit more complex stuff
that might work too
i'm sure there's a better solution, but it's low IQ as hell and it works for me
well, i was using a tutorial for this little game, and then added a few things seperately as a project, and a continuation is due somewhat soon, so i've been trying to add a few things
i wanted to add some other features, but i kind of had to simplify them since its kinda complex for me
@summer stump how come?
see there's always a better solution
Pretty sure the pros have an entire sound manager with an event system that tells them when and where an specific sound should be played but...
I am not that 🤷🏻
ah so instead of just audioPlayer.Play() do audioPlayer.PlayClipAtPoint ?
it's a static method
so don't call it on whatever object you have
call it on the AudioSource class itself
Yeah, or just do a coroutine to play the sound and then destroy it after the sound is done
Destroy already has an overflow for that
overload?
Destroy(gameObject, [delayTime])
Yeah, but waituntil is more dynamic
here you have to specify a static amount of time
Destroy with a timer would work too though
doesn't the method that you sent already do that tho?
im not sure how to do that sort of stuff i can check it out, but first i'll look at PlayClipAtPoint and see if i get the audio playing from that
Sure, not really needed though
What is needed and what makes things easier are two different things.
what would the point be of implementing your own destroy timer if the method does it all for you?
It creates a new separate object and destroys it
Who said a timer?
ah, as opposed to keeping the same object and then destroying it later?
this sounds sarcastic
it was not
it was a genuine expression of me realizing the difference
hm, seems kind of asinine to keep the same object tho
i mean, i guess you get the performance benefit of not creating a new object
but at that point you're splitting hairs
I mean, as everything here, you can get pretty similar results with very different ways
There is no correct way, just the ones that do work and the ones that don't
How is that splitting hairs.... when you have a lot of objects (like lasers firing often) it is a non-trivial difference in performance
i meant in the case of their game
They have to wait for the animation too already
I mentioned their use case
Lasers
yeah, but their game is not going to be having performance issues
do i need position and volume for it?
yeah
I literally have no idea if even "hiding the object" would requiere less procesing that instantiating a new one with just a new audio clip, seems pretty insignificant difference in performance to me
Position yes, volume is an optional parameter so no
1st arg is the sound, 2nd is the position, 3rd is volume optional
yeah, okay so transform.position should be fine i think
And I have never resched to the point that I need to use the profiler, yet
really?
i've needed to use it before to see where memory leaks were happening (because i'm stupid and my code looks like a 3 year old wrote it)
now im getting and error
"Member 'AudioSource.PlayClipAtPoint(AudioClip, Vector3)' cannot be accessed with an instance reference; qualify it with a type name instead"
like i said
Dunno, not like I have done anything huge
it's a static method
oh
Did you read the docs? It has a code example
Though I am fearing that in few weeks I will have performance issues if I keep adding powerups that can combine the way they are doing right now XD
If they are firing a few dozen lasers or more a second (like a bullet hell), it would make a difference. If only a few, it wouldn't
ah, yeah for sure, i wasn't thinking about the scale of like 50+ objects, just around a few
i saw the code example, but im not entirely sure uh, you said call it on the class?
yeah
and yeah its only a few lasers, nothing crazy
I dunno the scope of the game 🤷♂️
better 2 be cautious like u were
Then yeah, playclipatpoint is simple
It would, you could also pool it if you want to have it superpolished, but once again, not really needed
It would be pretty surprising if coordinating object creation between C# and the C++ Unity engine would be cheaper than changing some state on it.
does invalid scene equal non-existent scene?
wait idk if im thinking of it right, im not sure what the class is exactly? at least in this code, would i put a new if statement in the update?
So... changing several states is likely, most of the time, less consuming than instantiating a simple empty with just a single component?
im not sure where in the code i would put it i guess?
Well of course
Depends on what you mean by changing several states I guess. But most likely yes
I would do it in the collision code
Maybe. Share the context of where you see that
Is it from a build, an error in code, trying to open a scene asset? Where
In runtime, I want to unload a scene if it is loaded. GetSceneByName() always returns a scene, how do I know I should unload?
in the if statement for it right?
that's where i had it
i feel like an idiot but what's the difference between controllerMove and controllerMoveInAir?
ie which one should I actually use?
Not sure. If the if statement is to validate the collision, then sure
the if statement is for seeing if the laser has hit an enemy, so then it does all of the other things
So it us an error when you run the code to unload a scene? Do you have another scene loaded?
and i tried to put the playclipatpoint there, but it came up with that error since its a private void right?
this is the code rn
oh
What is this? CharacterController has Move and SimpleMove
or is it because i have the audiosource and audioclip not in the if statement?
im not entirely sure if thats what is needed for it to work
PlayClipAtPoint is static. You are using audioSource (a reference) instead of AudioSource (the type)
huh so move in air is not something that's native to unity*? i'll ask them about it
Nope, not as far as I've seen
Have you googled it?
I just want to create a method which will unload a scene if it is loaded. It can happen in multiple cases: when another scene is loaded, when no other scenes are loaded, there is no definite context except the fact, that there cannot be multiple instances of the scene running. Should I unload the scene only if I find the scene with this name?
I don't have any errors, I'm just trying to create a safe unload method
You can't unload a scene if no other scene is loaded...
then there will always be a scene
Well, you haven't really explained in which cases a scene should be unloaded. Just "when it is loaded" but that doesn't make sense, because then you would just immediately unload any scene you load
You can do it however you want, so there is NO "should"
It is not an answerable question
ohh
nothing comes out of google, i'll ask playmaker if they know anything
Lol, imagine unity were asking about the context before they created any method in their API 😄
What?
ahh nice okay cool
its working now, thank you, i think i can use that to make the other sounds i'll need work too thank you so much, sorry i didnt get what you meant at first
I want to create a method to unload a scene safely, if it exists. That is the only relevant info.
It can exist. It cannot exist. It is not a subscene, so whether other scenes exist is irrelevant. Since other scenes don't affect this one
No problem, glad it works!
Ok... well, that is different than what you explained before. You just want to be able to unload a scene... maybe explain that clearly next time. You said unload a scene "when it is loaded" (which I took to mean at the moment it was loaded)
We do need context to answer things. And getting snarky about it is unproductive
I said when it is loaded, because unload throws when the scene is unloaded. And I want to unload safely
yes, it isn't safe, it can throw. And not clear what exceptions to handle.
Well yeah, check if the scene is loaded first...
thank you, yes, this is what I was looking for.
So the method would look like:
if (SceneManager.GetSceneByName(sceneName).IsLoaded()) UnloadSceneAsync
seems like an odd thing to need at all
not at all, e.g. a disconnection in a game, which can happen during a scene transition. Next scene hasn't been loaded yet, previous scene has been unloaded.
But during disconnect you want to unload everything
I would prefer keeping track of which scenes ARE loaded, but sure.
I assume this is for additive scene loading?
even the case you suggest does not make sense. If you disconnect, simply go back to the main menu. If its not loaded yet, how is your previous scene unloaded? How will your method help if you are checking isLoaded?
this method implies you're gonna go through every single scene name and try unloading it
maybe yeah, will be better to keep track of things. The scene is unloaded additively, yeah, but can only be loaded once.
"Simply go back to the main menu" can mean different things. Menu is not the same scene in my game, it's a "root" scene, different from gameplay scenes, which server loads for clients.
Server is the only authority which triggers scene loads/unload, but disconnection is the case where server cannot do it's job, so the client has to do it themselves before connecting again.
I dont see how any of this is related. your game is gonna have an initial scene at some point. Just go back to there from the client, that is what a ton of games do when disconnected
yes, I do that in addition to unloading gameplay scenes.
iirc loading a scene with LoadSceneMode.Single should unload all the other scenes for you
didn't know that, thanks
With the exception of DontDestroyOnLoad
But that is kind of the point of that
Is this possible or should I just convert teh structs to classes?
-Make an array of structs
-Check if a struct is null
-Allow the struct to become null in the array.
By default, structs cannot be null. They are value types
You could declare it nullable. But better might be to have a bool field called initialized or something
What would be the purpose of checking if it is null though? Because there may be a better way to handle it
So I have an array of 5 ragdoll infos.
Aftera certain period of time I want them to become null
but actually my approach is wrong, i could just use Time.time to structure it differently
ill figure it out thanks
can i ignore multiple layers on raycast hit?
lets say i have to ignore no.17 and 18 layers
Use a layer mask to include or ignore whatever layers you wish
Yes
im trying to make my sprite move continually but right now it only moves once when i click the button i assigned it to, how do i make it move without stopping.
void Update()
{
if (Input.GetKeyDown(KeyCode.RightArrow) == true)
{
myrigidbody.velocity = Vector3.right * givenvalue;
}
}
}
that is the code im using
"givenvalue" is just move speed
Use GetKey
Instead of GetKeyDown
thank you!
Your problem is you have some other code overwriting the velocity elsewhere
Velocity would otherwise stick
Yeah, I should have read further. I jumped when I saw GetKeyDown
(not accounting for friction etc)
So, check any other code for velocity =
That would be the first thing to check at least
public float givenvalue; my velocity is tied to this so i can see in game to make small tweaks quickly
It could also be an issue of friction in which case you need to deal with the friction either with a custom physics material or just by doing what aethenosity said
That's nice but not relevant to what we're saying
oh okay
sry, im really new.
this is my first game ive made without a step-step guide
i have an item class, having some data in it. the item class has one instance for each item, so i want to hardcode these instances and then reference it from other scripts. but, my item class has a sprite property (an image used for UI of that item), which i can't assign in a static script. any workaround?
Why not use ScriptableObjects?
That's exactly what they're for
is it possible to get data from a scriptable object into a static script?
What do you mean by "static script"? Why do you need a "static script"?
Everything is possible
static class, my bad
Same question
what about using a scriptableobject data in another scriptableobject?
If you're using a static class as a beginner you're doing something wrong, to be perfectly honest
Not a problem
i've been using static classes for referencing, so switched one script to scriptableobject now requires me to make each on a scriptableobject
not that bad though
Learn to deal with references properly instead
You almost definitely didn't use a static class though. You probably have a static reference field. Static class is a different concept
That is a really bad reason to use static classes.
https://unity.huh.how/references
how do i serialise a jagged array
Either restructure it to an array of objects containing arrays, or use a different serializer that supports jagged strays
what is an array of objects containing arrays?
Which part do you not know?
[Serializable]
public class Container {
public int[] data;
}
public Container[] containers;```
Literally an array of objects containing arrays
im curious what youre using static for
how would there be multiple items then 😆
static instance1; static instance2; static instance3..
yikes
hi i try to make a turret placement system with raycast 3D in unity but i try to make that dont put my turret if the ray touch a "obstacle" object the code:
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hits = Physics.RaycastAll(ray, Mathf.Infinity);
foreach (RaycastHit hit in hits)
{
if (!hit.collider.CompareTag("Obstacle"));
{
if (hit.collider != null && hit.collider.CompareTag("map"))
{
tourelle1Renderer.material.SetColor("_Color", Color.green);
Vector3 turretPosition = hit.point;
Vector3 turretOffset = new Vector3(0f, -0.5f, 0f);
turretPosition += turretOffset;
transform.position = turretPosition;
if (Input.GetButtonDown("Fire1"))
{
Destroy(gameObject);
putTurret1 = true;
}
if (putTurret1)
{
Instantiate(tourelle1placable, transform.position, Quaternion.identity);
}
break;
}
}
}
}```
that just pass through the obstacle
you are using RaycastAll, the point of that is to pass through objects and get every single object hit within that line
how can i use single raycast?
for getting the first thing i hit
just do Physics.Raycast then
like that ? RaycastHit[] hits = Physics.Raycast(ray, Mathf.Infinity);
no, raycast only returns one which is gonna be the first object hit
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
oh i see
After a few fruitless searches
Anyone know what Controller Move In Air is? It just exists and my only asset used is Playmaker
can i just dont change my raycast and check if one of my hit are a certain tag
you are already doing that, twice in your code...
did you write this code yourself or is it AI 🤖 generated
#📖┃code-of-conduct dont post AI code
you dont even know what the code is doing, obviously its not gonna work
Start with just using Raycast (link above), and experiment around with it. Debug the names of objects that were hit, then try expanding your logic based on that
i not really have the time xd its for a school project
or you did have time to learn but just started working on it last minute. Either way, you arent making a functioning game by guessing, so get to experimenting and learning
Is there a way to expose this function to a UnityEvent? ScreenPosition is a public enum that is markes as serializable.
public void MoveRectToTheOutside(ScreenPosition targetScreen)
{
MoveOutSide((int)targetScreen, null);
}
The function should move the RectTransform outside of the screen, but exactly one screen above/to the right/below/to the left. I'd like to pick the direction in the inspector via a UnityEvent on my button-component, but the function does not show up. I am using Unity 2020.3.12f1 but will probably upgrade to the newest 2022-LTS version soon.
Guys i dont know what to do
i dont know too
So this is in the editor first and then as a build second? I think without a little bit of explanation there is no way to help out. Here are some pointers of what could be wrong: https://forum.unity.com/threads/editor-vs-build.1479954/
i really dont know what could be going wrong
so when the charachter jump its supposed to disable the box collider and swap the tile texture
if (Input.GetButtonUp("Jump"))
{
if(RedOn)
{
RedOn = false;
}
else
{
RedOn = true;
}
}
this is the code for jump
if(RedOn)
{
Tilemap RedTile = RedGrid.GetComponent<Tilemap>();
Tilemap BlueTile = BlueGrid.GetComponent<Tilemap>();
RedGrid.GetComponent<TilemapCollider2D>().enabled = true;
BlueGrid.GetComponent<TilemapCollider2D>().enabled = false;
RedTile.SwapTile(TileGrid,Tile);
BlueTile.SwapTile(Tile,TileGrid);
}
else
{
Tilemap RedTile = RedGrid.GetComponent<Tilemap>();
Tilemap BlueTile = BlueGrid.GetComponent<Tilemap>();
RedGrid.GetComponent<TilemapCollider2D>().enabled = false;
BlueGrid.GetComponent<TilemapCollider2D>().enabled = true;
RedTile.SwapTile(Tile,TileGrid);
BlueTile.SwapTile(TileGrid,Tile);
}
code for switching the tile
but as you can see it only turns off the box collider and doesnt switch the tile texture
How do you pause the animation during runtime, I wanna test soemthing
if (Input.GetButtonUp("Jump"))
{
if(RedOn)
{
RedOn = false;
}
else
{
RedOn = true;
}
}
this is the code for jump
if(RedOn)
{
Tilemap RedTile = RedGrid.GetComponent<Tilemap>();
Tilemap BlueTile = BlueGrid.GetComponent<Tilemap>();
RedGrid.GetComponent<TilemapCollider2D>().enabled = true;
BlueGrid.GetComponent<TilemapCollider2D>().enabled = false;
RedTile.SwapTile(TileGrid,Tile);
BlueTile.SwapTile(Tile,TileGrid);
}
else
{
Tilemap RedTile = RedGrid.GetComponent<Tilemap>();
Tilemap BlueTile = BlueGrid.GetComponent<Tilemap>();
RedGrid.GetComponent<TilemapCollider2D>().enabled = false;
BlueGrid.GetComponent<TilemapCollider2D>().enabled = true;
RedTile.SwapTile(Tile,TileGrid);
BlueTile.SwapTile(TileGrid,Tile);
}
Is the order in which stuff is picked up in physics.SphereOverlap ordered by how close it is to the centre of the sphere?
no, the order is random
nope
A UnityEvent can only access a method with:
- no parameters
- 1 parameter
- parameters that are bool/ string
- probably int and float too
For health systems which i believe the health variables should be best kept as private integers,
- I should have a maxHP component and a currentHP component for sanity's sake, correct?
- If this health value should be able to be influenced by equipment and level etc., is it possible to affect this maxHP component by another script, or I should put those variables that would affect maxHP into the same script?
- Does using [SerializeField] allow other scripts to reference private values, or they must be a public value regardless?
Are you confusing "property" or "field" with "component"?
-
yes you would need to separately track max and current HP
-
if you want it to be modifiable by things you'll need to have a slightly more complex system with temporary modifiers that can be added or removed (and perhaps permanent ones too like leveling)
-
SerializeField makes the field serialized. It doesn't make it public. It's highly discouraged to use public fields.
it's been 3000 years since i touched unity so i kinda don't remember how to do things already
How do I get and utilize integers that are supposed to be private if it's not possible to access it from other scripts?
Use accessors of course
not really even a Unity thing
just a general OOP thing
if you need to access them from other scripts, they are not supped to be private? that's a bit of an oxymoron
you can and should make your fields private
even if you want them accessed by other scripts
a public field is completely open to unfettered manipulation from the outside
with an accessor you can carefully control the access as you choose
yeah, I'm gonna have to disagree on that one
Feel free to disagree
Public fields are bad practice. Do yourself a favor and keep your code readable by exposing as little as possible.
If you need to expose variables, use a getter-property
there is no functionally difference between this:
public int MyIn;
and this:
public int MyIn { get; set;}
unless you are using a library that relies on the auto-generated code for reflection / weaving purposes.
This is why you don't use a setter in the property
Also there is a difference, properties are expected to be the thing you set, and your IDE actually documents what things access it
With a field this is guesswork, or manual searching
Pretty much everything in c# assumes you work with properties when it comes to setting and reading data.
an additional question
I understand that maxHP should be private, but what about currentHP? is it also beneficial to make a private+getter or just set it public (since it's likely it will fluctuate across the game)?
There's a mindset difference. While you're typing a property you have some more time to think wether it should have a public setter.
There should be a single thing managing these settings and you should make sure you are making it modify a private field. Anything else could fetch this current state from a property with a getter.
Where are you storing the variables would determine that
A game controller should be able to handle most if not all of your variables
Yeah of course not. There's no point in using the second one and nobody suggested you should
For something like MaxHealth you don't want people meddling with it from outside
With anything in c# I mean the functionalities you implement in c#.
it should be
[SerializeField]
private int _maxHealth;
public int MaxHealth => _maxHealth;```
or using private setter
but likely you'd want an event etc on the setter. This gives you the fine grained control over the thing you need.
Now I have a question, do serialized private variables mess with the game similarly to how public variables can?
what do you mean by "mess with the game"?
Define mess? I'm not sure what you mean
Ok, public variables occasionally won't update when you change the code in the script
They don't randomly refuse to change, I don't know what you mean
you mean when you update the field initializer? They're still serialized, so that will still happen
Do you mean setting a value which is not reflected in the editor?
that's an expected consequence of serializing something
there's nothing "occasional" about it though, it's completely well defined behavior
The editor doesn't like to update variables when the script changes
Of course not. It respects your serialized value
as it should
That would be crazy if it overwrote all of your assets
Pretty sure you can reset a component's context in the editor if you want them updated
Then it would overwrite it
Dang, I was hoping to see the variables without locking them in the editor
Locking?🤔
Regardless of how I modify the variables in the script, unless I set an on start function to fix all of them, I have to either reset the script or remove and re-add the variables to get them changed in the editor
I'll just swap to non serialized privates ig
Why would you change the value in the script every time?
on an unrelated note, is this more "efficient" than private+accessor, or the difference is minimal to non-existant?
It's supposed to be a default value for each component. Not something you change periodically
thx btw
I like to test them while it's running, and when I find a value I like, I usually want to hardcode the value so I don't lose it
There's no difference apart from the compiler adding an extra method between your call to the field. This change is negligible.
thx
If you want you could get rid of this if you really care with aggressive inlining
so I've got this code here which properly updates a progress bar, ```cs
public Image barImage;
[Range(0f, 1f)]
public float fillAmount;
public void GradualBarUpdate(float fillValue, float fillDuration, bool tapers)
{
barImage.gameObject.SetActive(true);
StartCoroutine(SmoothUpdateProgressBar(fillValue, fillDuration, false));
}
public IEnumerator SmoothUpdateProgressBar(float fillValue, float fillDuration, bool tapers)
{
barImage.gameObject.SetActive(true);
float elapsedTime = 0f;
float startFillAmount = barImage.fillAmount;
while (elapsedTime < fillDuration)
{
float t = elapsedTime / fillDuration;
fillAmount = Mathf.Lerp(startFillAmount, fillValue, t);
Mathf.Clamp(fillAmount, 0F, 1F);
barImage.fillAmount = fillAmount;
yield return null;
elapsedTime += Time.deltaTime;
}
barImage.fillAmount = fillValue;
if (barImage.fillAmount >= 0.97F)
{
BarHasFilled();
}
}
It works, which is great, but my initial approach didn't work, it just updated instantly and I wanted to double check why. I thought that how I used time.Deltatime here would be enough to show a smooth update, but it didn't work as I expected. What am I misunderstanding that led to my first approach not working?
```cs
public void GradualBarUpdate(float fillValue, float fillDuration, bool tapers)
{
barImage.gameObject.SetActive(true);
float elapsedTime = 0f;
float startFillAmount = barImage.fillAmount;
while (elapsedTime < fillDuration)
{
float t = elapsedTime / fillDuration;
fillAmount = Mathf.Lerp(startFillAmount, fillValue, t);
Mathf.Clamp(fillAmount, 0F, 1F);
barImage.fillAmount = fillAmount;
elapsedTime += Time.deltaTime;
}
if (barImage.fillAmount >= 0.97F)
{
BarHasFilled();
}
}
when and where are you calling GradiualBarUpdate?
Also your Mathf.Clamp(fillAmount, 0F, 1F); line isn't doing anything whatsoever
anyway all this code is pretty massively overcomplicated I'd say
On another object's interact method, so this will be when you are in proximity and have pressed E once ```cs
public class MainObjective : MonoBehaviour, IInteractable
{
public ProgressBar interactionProgressBar;
private void Awake()
{
interactionProgressBar.OnBarFilled += ProgressComplete
}
public void Interact()
{
interactionProgressBar.GradualBarUpdate(1F, 2F, false);
}
}
float targetFill;
float currentFill;
void Update() {
currentFill = Mathf.MoveTowards(currentFill, targetFill, fillSpeed * Time.deltaTime);
barImage.fillAmount = currentFill;
}
public void SetFillAmount(float fillAmount) {
targetFill = fillAmount;
}```
I would just do this^ much simpler. No coroutines. Less code.
I just didn't really want to put it in update since it follows the process of 'Press e -> Start filling -> Finish Filling -> Destroy ui element' having it constantly update seemed a bit redundant
so have it disable itself when it reaches the fill amount
¯_(ツ)_/¯
(and re-enable when setting a fill amount)
you can use that logic for the event handling too.
float targetFill;
float currentFill;
void Update() {
currentFill = Mathf.MoveTowards(currentFill, targetFill, fillSpeed * Time.deltaTime);
barImage.fillAmount = currentFill;
if (currentFill == targetFill) {
enabled = false;
OnBarFilled?.invoke();
}
}
public void SetFillAmount(float fillAmount) {
targetFill = fillAmount;
enabled = true;
}```
is .MoveTowards much different to lerp?
the way you're using Lerp they will do the same exact thing
just constant linear motion
anyway your initial approach here didn't work because you didn't have a yield in the while loop
that led to the loop just running to completion instantly
so it's not got enough time between runs to actually see the bar move
I mean it all happens within a single frame.
There's not enough time sure but also the game doesn't even render until the end of the frame
Yo guys I want to add velocity to a character upwards but using AddForce is wrong as it adds force based on the players velocity but I want the force to be fixed. Anyway to do that?
two differnet hings
SetActive activates/deactivates a GameObject
enabled just enables or disables the script
What do you mean by "AddForce is wrong as it adds force based on the players velocity"
And what do you mean by "I want the force to be fixed"?
so the same as ticking the box on the component in the inspector?
AddForce does exactly whatever you tell it to.
ah, that's good to know
Sounds like you don't want the force to be fixed. You want the resulting velocity to be fixed. In Which case you shouldn't be adding a force at all, you should just be setting the velocity.
Yeah this is definitely a lot simpler than what i ended up doing :/
Still learnt from it though
if a gameobject is set to inactive I take it that isn't just 'not visible', but cannot do anything
Basically, idk whats going on but when the player is moving and AddForce runs, the player shoots up but when the player is stationary, the AddForce that runs is very little
but why does it work in editor and not the build
You'd have to show the rest of the code - but for one this should be an Impulse force if it's a one-off thing.
I just reposted your code I didnt fix anthing
I was making a 2d game like flappy bird as my first project. I wanted to add an invincibility potion where after the bird comes in contact with the box collider of the potion sprite, the box collider of the pipes are turned off for some time. Can anybody tell me which unity function can be used to accomplish this?
I know but im still confused
can someone pls tell me why this happens
heres the video again
You dont need to use obs, windows has a new feature where you can screen record if you press printscreen
whats the shortcut?
Id just coroutine the box collider on the player sprite
Thats really weird though
Printscreen
As seen by the video if the player just jumps on the enemy it boosts a little bit up but if the player drops from a small height then the player wont jump. Doesnt that mean AddForce depends on velocity?
So i should create a function where when player comes in contact with the potion, i turn off the box collider of the player?
Yeah that would be easier, but ideally you just flip a bool like canDamage = false
if i change a value (like SubEntityData) inside originalProfile, will it also change the one inside blackboard.AttackProfile
No it means AddForce is additive
like, is originalProfile an exact copy, or does changing it also change the place i got it from
0 + 5 = 5
-3 + 5 = 2
that's all
So again it sounds like you don't wish to add a force
it sounds like you wish to set the y velocity
myRb.velocityY = whatever;```
(assuming you're in Unity 2023+)
OHHH I see
guys pls help me or is this not a beginner problem
I cant help friend but post the problem to advanced and see
ok i will see
you need to debug your code
this means taking concrete debugging steps to see what's going wrong. Log statements, attaching a debugger, etc. to test your assumptions and see what's going wrong.
Oh wait no im using 2022
Is it different?
yeah you'll just have to write it a little differently
myRb.velocity = new(myRb.velocity.x, whatever);```
just a little less nice
why does this keep appearing, im lost ngl
well you're looking at the wrong script
read the error message
the error tells you which script and line number to look at
0.Preciate it man
You need to look at WeaponUI.cs Line 15 @cinder crag
how do i do that
anyone got an answer for this?
anyone knows?