#💻┃code-beginner
1 messages · Page 532 of 1
the only place I'm calling the coroutine from outside of the script is in a different script in start which is a singleton
That is not how you do StopCoroutine
you need to cache the routine as a variable and pass that as the parameter
ah
private routine myRoutine
myRoutine = StartCoroutine
StopCoroutine(myRoutine)
some psuedo-ish code
There is also StopAllCoroutines. Didn't look close enough to see if you have any others in that monobehaviour, but that is a choice too, and doesn't require caching anything
i think ive got it now, thanks!
Should this be in a different channel?
Seems like the right channel. What happens when you double click a script file inside unity?
i also has a "starting visual studio" pop up but nothing changes after it finishes
i found this discussion thread but couldn't fix it
Did you recently install visual studio? If so, have you restarted your computer since then?
am I crazy or this should work?
I guess another important question is, have you EVER been able to open your script in vs?
StartCoroutine(MoveCoroutine())
Only the StopCoroutine needed to be changed
You are crazy
what if I want to call it from another script?
This is my first time ever dealing with unity, so i should restart my pc?
Make a public method that starts it
what's the IEnumerator overload for im confused
yes
you can only call it by string though it seems no?
No
In the class you have there:
public IEnumerator MoveCoroutine() {
//blah
}
public void StartMove() {
moveRoutine = StartCoroutine(MoveCoroutine());
}
In the other script
myReferenceToScriptA.StartMove();
Something like that
I've done that, but maybe I did it weird with my class set up
Likely a reference issue (pointing at a different instance than you expect). But can't say
so this is the SnakeController class: https://hatebin.com/ihogonhkmq and this is the GameManager class that is meant to hold the coroutine: https://hatebin.com/aslaqardbj
it doesn't throw any errors but calling StopCoroutine(GameManager.Instance.moveCoroutine); in the SnakeController class doesn't stop the coroutine
Ah yeah, you are starting it in SnakeController, so this won't work:
StopCoroutine(GameManager.Instance.moveCoroutine);
Store the routine in SnakeController, not GameManager
I mean.... I guess it could work, but why?
I recommend what I wrote above
Then just do this inside GameManager:
snakeController.Move()
oh wait yeah im an idiot i could literally assign it to SnakeController via the gamemanager
Restarted my pc and it's the same thing, would full shutdown and full reboot make a difference?
hmmm it still doesn't work for some reason
Click View>Show Solution Explorer
https://hatebin.com/qqgrwbinzk this is the new version following what you told me (at least I think this is what you meant)
This should work, but add some logs.
Well, are you calling snakeController.Move() from the GameManager? Because then it won't loop, just be called once. You likely want a third method like StartMove that ONLY calls the coroutine
because Move doesn't actually start the coroutine anywhere, just stops it
this is all I'm doing to it from the outside, aside from instantiating ofc
Ok... I generally never start a coroutine in another class, so not sure if that would work
Can you try the indirect method I said above, just a single line public method that starts the coroutine, INSIDE of snakeController
Right click the solution and click reload with dependancies
Honestly, this is a very weird setup. It would be easier to just use update in your case.
May I ask why are you doing this?
Seconding the update route. If you want a delay, a float timer or a coroutine with a bool would probably be better, called in update and runs once
I just want the GameManager to have control over when the snake starts, in case I want to have it instantiated but then play some animations or something
No judgement btw, just wanna know the reason
Could be as simple as a bool called canMove then
snakeController.canMove = true
A simple bool and a check in update would work for that.
What they said.
but then id also need another bool to see if coroutine is playing no?
You wouldn't need the coroutine at all anymore with that
Or at least as is. If it's a timer then no, you wouldn't need to check if it's running. Just the same bool toggling on and off
canMove = false
waitForSecondsRealtime
canMove = true
ah like that okay
Or even better - enable/disable the controller script.
whats the benefit of doing that?
You are a god send tysm
Ah sick. Glad it worked!
It's more "appropriate" way from unity perspective.
The rule of thumb in coding is "keep it as simple as possible". Using the enabled property of the MonoBehaviour would save you from defining an extra variable
ive actually been wondering - is there any performance downside to that? like maybe really big scripts cause hiccups when re-enabled or something
Unless it's a bunch of stuff being enabled and disabled every frame, not really, no.
Only if they have any/heavy logic in onenabled/disabled. Otherwise it's just like setting a bool(mostly)
For your use case, you are most likely fine
Some people do over-optmize with this stuff. Like, I know some devs who don't even disable the UI, just reduce the alpha to 0 and make it not interactable.
yeah its been a big focus on my course so far since we are focusing on mobile game dev, its a lot more important on mobile platforms but as a newbie its often hard to tell what is too much and what is too little
also I got it to work with the canMove method!
Here's the best rule you can follow in terms of optimizations: don't worry about it untill there's an actual problem. Test and profile your game frequently on the target platform/device and when there is actually an issue, investigate it.
With experience you might learn to write better optimized code without even thinking about it.
That being said, it's fine to ask such questions.
Do you guys have recommendations on following guides/ tutorials that uses best practices? I'm going through a game dev tv course and it uses 'FindFirstObjectByType' quite a bit and it doesn't sound like the best way to do things.
unless im wrong
nothing wrong with that function if it used once for caching
ofc there are better patterns like DI for example but its not really a big deal for game. No you dont want to use that function like update for exmaple
they use void update() for all their tutorials lol
i get it though its a beginners course and thats bad practice
they're calling FindFirstObjectByType in update?
no sorry not that specifically
ohh okay. Update itself is nothing wrong
just be mindful what you do since that runs every frame
hence scanning every heriarchy object for a component is probably not the best every frame (and unecessary)
Oh okayy thank you 👍 yeah i thought running it every frame would hit performance a lot but I'll learn profiler to see the results when its time to make a game. I want to make the jump to 'just develop' soon cause its been almost 2 weeks into unity and i really learn best by diving into the unknown - switching in UE and its a big difference but im loving it
well the UI is a big difference* haha
and C# keeps it all in one file where C++ needs a .cpp and .h file
yes using unreal is like using a chainsaw to slice bread
btw check out the learning material pinned in this channel, its pretty good stuff there
Hey y'all! There's something I'm trying to figure out here and I was hoping someone here would perhaps have a suggestion.
I have a function that I want to change scenes after certain conditions are met. It isn't just an "if" but more for it to wait until the conditions are met. However, the function is handling refs so I can't make it an IEnumerator, therefore it can't yield return a coroutine to load the scene. I was wondering if anyone had any ideas on how I could accomplish what I'm looking for?
There is only one code language for unity
Maybe set up a delegate or event that triggers the scene change if certain conditions are met
!vscode
There are beginner resources pinned to this channel if you're stuck getting started
Create the script from Unity itself. It will be setup as needed with some boilerplate to get you started
The links I sent you in #💻┃unity-talk go over how to setup the code editor and create scripts
I do strongly recommend it over youtube
I don't want to make one externally because this condition shouldn't be able to be met all the time.
The condition is a "wait until" type deal but I still do need the check for it stored within a larger if statement, if that makes sense.
Unless I can make the function call a coroutine that itself calls a yield return coroutine?
That one and then Junior Programmer at least
Essentials is just navigating Unity for the most part
game dev is a huge journey :3
thinking like a coder will be a journey itself but necessary
mine fried years ago so ill letchu know when i can relate 🤣
Yeah, there is a lot to take in.
me just saying this had me wondering if this might work now
If I call the larger "WaitForTextBoxAndLoadScene" coroutine in a void function, will it wait to load the scene until "WaitForTextBox" is done?
in other words using an IEnumerator to store the other IEnumerator that needs to yield return
I was being hopeful, this did not work lmao
Presumably you're also starting it properly with StartCoroutine?
Yes
Basically I need:
void function > if condition > (other code) > wait until [x] is met > load scene
and obviously those last two things don't really jive with the encapsulating function being a void
Some research says a helper coroutine may help so I'm trying that rq
Helper coroutine did it!
is Assembly-CSharp.csproj only used by an IDE like Rider or Visual Studio and not Unity at all? (ie if im using say Vim or Emacs, then .csproj files aren't needed?)
https://stackoverflow.com/questions/6446361/what-does-the-csproj-file-do
it's used for compiling.
more generally; if that file exists without opening an ide, then it's probably not specific to an ide
can anyone help me find the math for shadow depth maps. Ive been looking for literal hours and i cant find the math anywhere
Hey guys quick questions is this normal when using unity ? My code is grayed out it says - "IDE0051: Private Number 'Unit Update ' is unused". Wonder if anyone else experienced this ?
it's a bug with the most recent version of vs afaik
is there a way to remove or diable this ?
What kind of math are you looking for?
The math that describes how to create a shadow map and how to use a shadow map
That sounds more like an algorithm, rather than a specific math calculation.
In simple words it should be something like rendering the objects from the shadow source perspective into a depth buffer.
are algorithms not also math?
yep ive gotten that far but im looking for something more specific because i cant write code that says render(light pov)
They can contain math, but it's more than just that.
Well, this would usually involve issuing specific render commands to the GPU, setting up the GPU state, managing render targets. This is basically the job of the engine.
There isn't one specific math. It involves a lot of separate steps.
which steps
The ones i mentioned earlier
what you said earlier could apply to literally anything under the umbrella of rendering
im talking specifically about a shadow map
Shadow map is rendering though. It's just rendering the objects from a certain perspective.
right, so whats the math to do that?
Are you asking how to calculate the depth of a pixel in the shader?
yes
Then say so from the start lol
i thought i did
No. You were very vague. As I said, rendering the shadow map is a process with many steps. Calculating the pixel depth is just one small step in the whole process.
Anyways, the way I understand how it's done is you take a vertex position in clip/view space in the vertex shader, pass it to the pixel shader with interpolation. And that's basically it. The interpolated value is the depth of the pixel.
what is clip/view space
It's a space inside the camera frustum usually having values from 0 to 1 iirc, where 0 corresponds to the camera near frustum plane and 1 to the far plane.
so how do i get that from a global coordinate of a pixel im trying to calculate the shadow depth for
You don't get it from a pixel global position. You first need to transform the vertex position to view space with multiplying it's position by the corresponding matrix. The result would be the vertex position in view space, which passed to the pixel shader would interpolate between the corresponding pixels.
"transform the vertex position", vertex position of what?
Of your mesh obviously. Whatever object it is you're rendering.
is that somehow different than the global position of what im trying to render
Of course. Meshes consist of many vertices - many positions that consist the object shape.
"Global position" - I assume you're referring to the object position is just a pivot point of the mesh.
what if my mesh is a single vertex
That's not possible. There would be nothing to render.
my mesh exists theoreically, there is no actual mesh its simulated
I think you can't have meshes with less than 3 verts physically.
my mesh exists as a single coordinate
Then it's not a mesh. Just a point in space.
ok well how do i determine the shading depth of that single point in space
The same way. Multiply the position by the view matrix.
what is the view matrix
You'll need to do a little bit of learning yourself. Google it.
i have googled it
it says to multiply by the view matrix but not what the view matrix is
or at least the sources dont agree on what it is
Then read from several sources and try to put that info together
ive been reading for literally over 6 hours
this is my last resort before i just give up and go back to api programming
Is there a specific thing you don't understand about it?
every single source mentions exactly what a shadow depth map is but not one says how anything is calculated
i understand its a series of linear algebra ops but idk which ones
It's not. It's a lot of simple math and other not math related steps.
ok given a position in 3d space, i multiply it by the view matrix
what is the view matrix
this?
Its a matrix. A bunch of numbers. I don't know how it's calculated. You usually don't need to know it, unless you develop your own engine.
Yes, this is a matrix, though I don't know what matrix this is exactly
To put it simply, a view matrix is one that when a position is multiplied by it, returns a vector corresponding to that position in view space.
[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
see now why couldnt they have just said a 4x4 diagonal
Because it's not
It's a matrix. The have certain rules that apply to them. It's a math concept.
ok but i need the numbers
Maybe move the conversation to #archived-shaders or #archived-code-advanced (if you need to do it on the C# side for some reason), because this is really not a beginner topic.
So? How does it contradict what I said?
You might be a beginner, but this topic is not.
And while we're at that, just a recommendation, but start with something simpler if you're a beginner.
i like this topic
ill move it though
It's like you're trying to construct a nuclear reactor in your background without any knowledge in physics.
im trying to gain the knowledge
i just cant find it anywhere
it feels like a secret recipe that is passed down but never written
Start simpler, get there eventually. There is a lot of prerequisite knowledge to what you're asking and you seem to lack it.
Quick question for my problem is there a work around with this bug ?
Either your IDE isn't configured or your class doesn't derive from Unity's Mono Behaviour component class.
am confused
It's not a bug.
ok I got that but , what would you mean your class doesn't derive from Unity Mono Behaviour component class.
You'd have to explain what you're confused about to get a proper response.
Ok for me what that I don't get is that for every project I open in unity Awake, Start and Update methods, like the image above are appearing gray out. I just don't understand why its doing this now.
It's a bug with the latest update for visual studio.
Or so I'm told.
Ok so am not going crazy then.I know someone already told me but I wanted to reassure am not going crazy
Is there a source for this?
Ill guess just leave at that and just wait until it gets fixed
thanks for the help @ivory bobcat and @alpine fjord .
I've seen several people bring up that issue in this server. But no I have no real "proof".
Heyo! I've got a doorway that my player can walk through on either side, and I'd like to enable post processing when the player walks through one side of the door (a box collider), and disable it when it walks through the other. I've attempted this script below, however it only resutls in post processing being enabled on either side of the door that the player walks through and I cannot for the life of me figure out why. I think I may be misunderstanding how Dot Products are calculated, does anyone know what the issue is? 😅
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;
public class DoorTrigger : MonoBehaviour
{
public Transform doorCenter;
public PostProcessVolume postProcessVolume;
private void Start()
{
DisablePostProcessing();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Vector3 toPlayer = other.transform.position - doorCenter.position;
if (Vector3.Dot((other.transform.position - doorCenter.position).normalized, doorCenter.forward) > 0)
{
EnablePostProcessing();
}
else
{
DisablePostProcessing();
}
}
}
private void EnablePostProcessing()
{
if (postProcessVolume != null)
{
postProcessVolume.weight = 1;
Debug.Log("Post-Processing Enabled");
}
}
private void DisablePostProcessing()
{
if (postProcessVolume != null)
{
postProcessVolume.weight = 0;
Debug.Log("Post-Processing Disabled");
}
}
}
Anyone know how to fix this problem i have with my jump?
I have my ground drag set to 10 so my player movement feels a bit less slippery
but when i jump my character barely goes anywhere in the air
i have a double jump too, so if i increase the force of the jump it might help the first jump, but the second jump would be way higher than it should be
with my ground drag being set to 10, i also move faster when i jump in the air which kinda feels odd
i cant really figure out how to get the right balance of having a non sliding character without manipulating the drag which in turn seems to mess everything else up
Are you using Input.GetAxis for your player controller?
im using Input.GetAxisRaw
Hm, weird there's sliding without drag then, since there shouldn't be any input smoothing
i tried messing around with physics materials and everything too, but couldn't really find a perfect working fix for it
(I personallydon't like using drag to recude slippery-ness, for the described issues, but I'm still a beginner :P)
You could try making the rigidbody kinematic while there's no input?
what do you use for it?
When I use GetAxisRaw it usually stops sliding as much :/
I'm unable to reproduce the issue - no errors whatso ever.
May code is grayed out it says - "IDE0051: Private Number 'Unit Update ' is unused".
#💻┃code-beginner message
Looks like an unconfigured IDE if anything.
hmmm, do you have your drag set to the default 1?
and no friction material on player?
because when i have no friction material on my player and the drag is the default 1, even with Input.GetAxisRaw my player slides when i let go of my input
0 🤷♂️
hmm, and you dont have a physics material on your player or the ground?
Nope
thats so weirdd
if i have no physics material and my drag set to 0, my player feels slippery
like i slide for about a half a second to a second after letting go of my input
Yeah I don't think that should be happening with GetAxisRaw, might be something else influencing it
hmm if it helps i can send my whole movement code if u wanna take a look, im not sure what it could be though
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Your public "groundDrag" variable is set to 0?
Oh you have some lerping for your move speed when you're dashing. That could be it
It's a bug. They probably just want people to make the sensible choice and switch to Rider lol
yea i tried setting it to 0, it was normally set to 10 before that go get rid of the slipperyness
ooh i think that only happens when im dashing though, so it shouldn't be affecting it when im not dashing i think hopefully
That seems to be the intention, but the transfer state code might not be triggering properly, might need to set up some debugging :P
I'm almost done updating VS. Will try to reproduce it.
Ah.. maybe I should cancel the update.. 😳
The latest verified was 5 days ago.
NOT fixed in 17.12.1
I'll verify if it persists in 17.12.2.
Alright, it's a no go.
did you just update it .. oh no LMAO
lol
Hello and good day everyone!🌹❤️
I have a little question.
In my game in have some datas that need to be sorted and used across multiple scenes. Like total scores, collected items and so on.
Is it better to save the records on a jason file based on a single scene save and load system or make a small local database for it? 🤔
Thank you for your time and guidance 🙏🏻
Whatever works for you. Usually using database is an overkill.
just use dont destroy on load to keep the script when loading new scene
Use a file and store it on a location where it persists (so not like the %TEMP% folder for example). Most commonly the AppData folders are used. As for the format, I suggest you look into encrypting the data or using a binary format. JSON is incredibly easy to modify so this is something you should use early on but definitely replace once you release your game.
Most games use a custom binary format where they know the order of bytes. It is impossible to modify unless you know what format you use. Alternatively use an encryptor for your JSON data.
This only matters if the data is not persisted, in which case I assume this is what they mean
Probably better if more context is given since it's unclear
she asked how to use sorted data in multiple scene
I get that, hence why its "probably better if more context is given"
So @lilac crow is this for persisting data so you keep your score when you start up the game at a later point?
I want to use this datas like total score for unlucking new abilities and other things, it is kinda a currency, some of them will be modified.
And I don't want to be restored to non when I reload the gaim or start it again.
That's why I want to store them.
Yup
Yes, then use files
Databases should not be used because you end up providing your game on user PCs where it is not a good idea to do this
If you were to provide a service which communicates data through an API or socket, then the serverside could very well use a database though
But locally you should just use files. Alternatively you could use SQLite since it provides the database as a file, but this has its own issues with encryption and such.
So JASON it is.
Here I come babe!!
.
.
Thank you all very much for your time and attention! 🙏🏻🌹❤️😘
guys any one of u uses the new input sys of unity
#🖱️┃input-system and checkout pinned resources there
The first sentence in the docs explains that?
Pretty sure ExecuteInEditMode is being deprecated in favour of ExecuteAlways
Docs only have one difference
To keep prefab editing mode open while in Play mode, use the ExecuteAlways attribute instead. If you do this, you must take care to ensure your runtime MonoBehaviour code does not modify the prefab you're editing in ways intended to occur only during gameplay. For more details, refer to ExecuteAlways.
I thought this is normal?
oh you're using VS my bad
So apparently, if you're having "Waiting for Unity to finished code execution." right at the start that runs essentially forever, it probably means there's an infinitely running code in an editor code somewhere.
I'm using a recursive function in my case, i would have liked if it eventually threw a stack overflow exception. Would have been easier to spot.
yikes, that sounds scary . . .
perhaps it was subject to TCO?
tail call optimization, where tail calls are flattened into a single stack frame, so it wouldn't trigger a stack overflow
seems like c#/mono don't support this, but maybe the architecture does..? this is kinda low-level stuff i'm not super well-versed in
A stack overflow exception only happens with an actual stack overflow
This is why recursion is something to be careful with
In this case you could perhaps use something like polly so it short circuits if you want to be 100% sure
hi how do i check if a button is pressed at the same time as one of the times stated in a list
what kind of button ?
on a keyboard
you need to be more precisely. you are aksing for ready code.
i have a bunch of times in a list and wanna check if a button is pressed at the same time as one of them
so how is the list declared
what does that mean
what is the type of your list
float
you can't check eqaulity for the exact time. you need to compare if the difference between the current time and listed time is within a certain threshold . . .
List.Add(Time.time);
it means what line of code defines your list
how do i compare anything to all the values in a list
the same way you compare two values against each other . . .
for loop
List in c# are very powerful you can do many things. Find,Select use linq etc
even .Contains
that will work thanks
no it wont, never test floats for equality
how come
because 0.000001 != 0.000000
i will be doing it within a range its okay
but .Contains wouldn't
then you still cannot use .Contains
I wonder btw speaking of floats
if you type 1 or 0 as float
are they really 1 and 0?
yes
but 1f - 0f might not be 1f
it's stuff like 16777217 and 0.6 that don't exist
yes, bc you're converting an integer into a float . . .
that's not a thing, no
that logic doesn't hold
also 0.0000000000000000000000000000000000000000000001 -> 0
though, that's not a float . . .
wdym by that
too many decimal digits (precision) . . .
what should i do then
you need to round your float
i do know for loops but im not sure what i am supposed to do with it
you compare results each iteration
loop through your list of times, get the difference between the current time and each iteration (element at the current index), then compare (that difference) to a threshold . . .
okay i get that thanks
I got a GameObject with a layer which collides with nothing and have a dynamic rigidbody
And it got a bunch of other child GameObjects with different Layer Overrides (they don't have rigidbodis)
Somehow, one of the childs collides with the object it should be unable to
What's going on
Judging from the context you gave? We don't know
no, probably not
The idea behind it was to make it so all child colliders only collide with stuff they are supposed to and send callbacks on the main rigidbody
do you know how to compare floats with an epsilon
Also, this is hardly a code question
yeah... eh.. sorry
i dont know epsilions
epsilon in math is an infinitesimally small number; in computing, we use it to define a threshold for saying 2 floats are equal
suppose we define an epsilon of 0.01, that means we want to define 0.99 and 1.01 as "close enough" to be equal to 1.00
and we can check that by doing abs(a, b) <= epsilon, to check that a and b are not more than epsilon apart from each other
(that epsilon is the infinitesimal float though, you don't want that for this usecase)
typically, i use my own threshold so i can control the range or precision of error . . .
Thank you for the detailed explanation
i totally get that now
although i am encountering issues comparing lists to floats
you should not compare lists to floats
you don't compare the list
you iterate through it
you should compare each float inside the list, to another float
that's what people were talking about with looping
"each" = loop
how do i extract each value from the list
loop
the list is literally a bunch of elements, thats what loops are for
iterate through each one
foreach to get them directly, or for to get the indices too
what would it mean for a number to be less than a list?
nothing
right, so i < List doesn't make sense
You want the maxmium of the list
i thought there may be something im not understanding ab it
have you seen loops before?
yes
revisit those resources then, maybe
iterating through structures is pretty fundamental; you'll need it more in the future, so best get comfortable with it now
an example. first one is on the house 🥄
int[] numbers = { 10, 25, 7, 69, 50, 12 };
int largest = numbers[0];
for (int i = 1; i < numbers.Length; i++){
var currentNumber = numbers[i];
if (currentNumber > largest){
largest = currentNumber; // update largest if current number is greater
}
}```
what have you tried or looked up?
Why would Rider automatically convert:
InventorySlotUpdatedSignal.Emit(
inventoryIndex: useIndex,
updateType: InventorySlotUpdateType.ADD,
oldItemContainer: null,
newItemContainer: newItemContainer
);
to
InventorySlotUpdatedSignal.Emit(
inventoryIndex: useIndex,
updateType: InventorySlotUpdateType.ADD,
null,
newItemContainer: newItemContainer
);
?
what happened when you tried it?
Is seems like there are syntax style arguments rules but it seem like I have to choose either positional or named, I wish I could just tell it to not change it
Hello
I don't understand why I get an error when I do this :
using UnityEngine;
public class SetPlayerSpawn : MonoBehaviour
{
private void Awake()
{
Debug.Log("Player spawn set to: " + transform.position);
SingletonManager.instance.playerSpawn = transform.position;
}
}
using UnityEngine;
public class SingletonManager : Singleton<SingletonManager>
{
public Vector3 playerSpawn;
}
Unity send me this error : ```
NullReferenceException: Object reference not set to an instance of an object.
SetPlayerSpawn.Awake () (at Assets/Code/Scripts/Player/SetPlayerSpawn.cs:8)
is it the singleton line (line 8)?
yes
then instance is probably null . . .
Why does this error appear? I’ve done everything possible and nothing works. I wanted to try with a tag, but you can't use more than one.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
double check that it's assigned before attempting to access it from the SingletonManager class . . .
the error is not even in the script you posted
What instance ? If I affected a new value of the instance, it's normal that null before no ?
your error says flashLighr.cs line 11. this is a totally different script . . .
seems you tried everything on the wrong . . . thing . . .
seems to be this line actually
if (handScript.mainHand == null)
most likely you don't have a valid reference for the handScript
a null ref error means you attempted to access the value of a reference variable that is not assigned (null). your job is to look on line 8 for any reference variables, those are: instance and playerSpawn. now you have to check that both of those variables have a value assigned to them before you execute this line of code . . .
i just change the name in hastbin sorry for confusion
It has the same name
then if i write this
if (handScript.mainHand.name == "flash")
the same error appears
right because you're still trying to dereference handScript
they're saying handScript is null. you need to assign it a value before attempting to access it . . .
It's fine. The work around would be to put a file in the root folder of the project with the contents suggested from the the temporary workaround/solution page:
https://developercommunity.visualstudio.com/t/Private-Unity-messages-incorrectly-marke/10779025?viewtype=solutions
I've tested it and it works. Very unfortunate that this must be done though..
You pimp
I understand that part, what I don't understand is how I'm getting that error if it's being assigned in the inventory script
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It likely isn't assigned and maybe not the object you think it is.
we're talking about handScript. is that one assigned?
yes
you need to log if the value is null for all reference variables to determine if they are actually assigned . . .
something is not assigned when you think it is . . .
before the error line, log the value of the variable . . .
private void Update()
{
if (handScript == null)
{
Debug.Log($"We don't have a hand script attached to this component - click me once", this);
}
else if (handScript.mainHand == null)
{
print("a");
}
}```Check if it's null before using it.
Click on the log and see which object highlights in the scene-hierarchy.
let me check that
The first output appears
And did you click the log message once?
What do i use to detect a button continuously be held down and what do i use to detect a button which was just pressed once ?
depends which input system you're using
old or new input system?
The legacy system
GetButtonDown for initial press vs GetButton for holding
Oh, I think I just found the problem
It's not assigned
bruh . . .
Sorry for wasting your time with a silly mistake
from the very beginning we told you it was the handScript . . .
always check and don't assume . . .
I'm really sorry, I hadn't understood it
hey, it's figured out. that's a win!
Hello guys, I'll get to the point. I'm really a newbie but I wanna learn unity and C#. I know most of you are professional and I need help. I'm waiting suggestions.
(I'm trying to make some projects)
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Learn and skip-around/do-things at your own pace.
An example of skipping to the programming essentials chapter.
Do note that there's more to gamedev than just programming though.
I just noticed my project doesn't have the .vs folder. At this point might uninstall both unity and visual studio code . Edited: Decided to use VSCode until VS fix there shit
Hello there, I would like to make a 2d mobile game with physics, and I was wondering what is the best course for this
https://www.udemy.com/course/the-ultimate-guide-to-game-development-with-unity is this the one? it has two 2d mobile games with a small amount of physics, but im a total beginner to unity and c# and I thought I will start with those two, thanks! =]
I have a button on a canvas that keeps changing it's position only after a windows build and only when I anchor it to the bottom left. When I anchor it to the top left, it stays in it's rect transform position of x:50, y:50.
But when I anchor on the bottom left (no change other than changing the parent's anchored position) it keeps changing it's position to Rect Position: X:-50, Y:-50 which is off screen.
Hey all I'm encountering an issue when trying to create a shader in URP, anyone have suggestions how to fix this issue? I can't seem to find anything online. Shader error in 'Custom/OceanShader': unsupported shader api at Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl(238) (on d3d9)
i have an array of an enum that needs to be displayed as a SerializeField in the Unity editor(see image for example), and i need to sort it(the array) to be in the order of declaration in the enum(see image). how can i implement this?
i would start with a flappy bird, angry bird, and a 2d mario clone. you'll find tutorials on youtube. i would do that before attempting to buy a course . . .
alright, but im trying to make something like Blek
https://youtu.be/JXv8eRkHlb4?si=2llujOCjDdyPvEDt
would you try something else, now that you know the target is something like blek?
Gameplay Video of "Blek" by AppTrendr.
iTunes Link: [https://itunes.apple.com/us/app/blek/id742625884?mt=8]
Subscribe [https://www.youtube.com/user/AppTrendr/videos?sub_confirmation=1] AppTrendr
The latest iOS and Android Gameplay, Trends, Review, Preview, Trailer, Cheat Code, Walkthroughs & More.
iTunes Description:
• Featured by Apple: B...
can the array have more than one instance of each enum member
no
why not just have a list of bools for each enum member then
it shouldn't have more than on instance of each enum member
you could use OnValidate or a custom method with the ContextMenu attribute. the method would get the length of the enum, loop, and cast each value using the current index . . .
you don't need the flexibility of a list, so don't use a list, use a more constrained structure
that way the validation is built into the structure
Hi everyone, kind of a beginner coder here and I was wondering why is the y value of my Cinemachine offset not changing with this code? What am I doing wrong?
EDIT: I'm trying to smoothly change my _currentYAngle from 4 (the initial value) to 10 when they enter a triggerbox and then back from their _currentYAngle to 4 when they exit.
Here is the script
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Oops, sorry! Here's a link to the code
https://hastebin.com/share/exigurupoz.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
There isn't any code in here that attempts to modify the Cinemachine offset
You're only modifying your own variable, which isn't used anywhere
_currentYAngle
Ooooohhh, now I understand!! Thank you very much! 😄
I need help with a script :using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileDeleteScript : MonoBehaviour
{
public float Lifespan;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
this.Lifespan -= Time.deltaTime; // Decrease the lifespan variable
void OnTriggerEnter(Collider other)
{
if (other.tag == "Zombie")
{
Destroy(base.gameObject, 0f);
}
}
if (this.Lifespan < 0f) //When the lifespan timer ends, destroy the BSODA
{
UnityEngine.Object.Destroy(base.gameObject, 0f);
}
}
}
this is on a prefab, and the ontriggerenter is not working
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok
oh, i'm blind . . . 🤦♀️
your OnTriggerEnter is inside Update.
IM A NINCOMPOOP\
It still is not working, how do i do a debug.log?
i would look that up first . . .
it is not debugging anything
did you read the links caesar and i provided above? make sure your objects are setup correctly to receive trigger messages . . .
ok
i think it was cus i did not do 2d
you need "2d" in the method name for that
welp, 2D is for 2D physics and colliders. it uses a different physics engine than 3D . . .
let's give it a try and see what happens . . .
I just edited it
How do i do a rigidbody trigger, im in unity 2021.3.37f1
is your method declaration correct now
my rigidbodys dot say trigger
if you follow the links you'll be able to check that you have everything. click on I am working in 2D to start from there . . .
then continue to the next link if you are not receivng a trigger message . . .
at the bottom of that page is another link if you still do not receive a message . . .
I went through the step and i think this is the problem
the site shows this
is your collider set to trigger?
the riggidbodys is this
if the objects are on the same layer, they will collide with each other. it would only be a problem if you manually change one of the objects' layers. by default, they're set to the same layer . . .
i'm talking about the collider, not the rigidobdy . . .
IT WORKS
i added a box colider 2d to the prefab!
you should have been able to look at this page from the links: https://unity.huh.how/physics-messages/trigger-matrix-2d
you can't collide with anything without a collider . . .
this is not an issue
Im confused?
physics layers are only an issue if you manually set layers for your GameObjects. if you did not, then it's not the problem. by default, all GameObjects are assigned to the same layer, so this is never an issue . . .
Ok
why does joints do this?https://hatebin.com/evjebqfmtr (btw some of the script is not written by me so it may be illogical)
are they perhaps colliding with each other
I solved it but dont know what I did.Changed the script a bit.Deleted complex things.
Hello, I have a text child of my button is there a way to rotate the button without rotating the text ?
button.image.transform.rotation
ive tried to rotate directly the image of the button but it doesnt work
When I call Button.GetComponent<RectTransform>().anchoredPosition = new Vector2(100f, -100f);
in the Start() nothing happens.
If I add a coroutine that calls the EXACT SAME THING -- Button.GetComponent<RectTransform>().anchoredPosition = new Vector2(100f, -100f);
but a second later, it works...
does the text have to be a child of the button? easiest solution is to just make them siblings. Otherwise you can always rotate the inside by the same amount you're rotating the outside, just opposite, to offset the rotation
how can i not see velocity in my debug panel for rigidbodies??
i remeber doing this before?
it's not there in the latest versions
wat
you can display the velocity by assigning it to a serialized field on some other component, or print it to the console
the rigidbody component's inspector is incredibly slow because of all the stuff it does to display things. simply viewing other objects can be an improvement in performance because of how fuckin slow it is
ah i see
does this effect runtime performace? i feel like i dont care if it doesnt
only runtime in the editor while viewing the component in the inspector
thats so stupid
but if im on the debug panel chances are i dont care about performance???
like idk wtf
typically people still care about the performance of their game while viewing debug info. just because you don't, doesn't meant that nobody else does. i gave you alternatives to view the velocity, pick one and stop complaining.
Oh yeah, it's amazing how much performance would take a beating if you got the inspector updating everything all at once
There's a whole separate debug menu for physics now
Pretty sure you can see it in there
Yeah you can track Rigidbody and Articulation body velocities there
I cant seem to get my slider to connect to my mixer audio to allow the player to adjust the audio in unity
this is the code that I have currently
with a serialized field for the mixer
{
bounceStenght += 1/100;
switch (collision.gameObject.layer)
{
case 6:
case 7:
logic.gameOver();
birdIsAlive = false;
myRigidbody.linearVelocity = Vector2.up * (1/bounceStenght);
break;
}
}
}
I'm getting this error
bounceStenght is likely 0
UnityEngine.Rigidbody2D:set_linearVelocity (UnityEngine.Vector2)
BirdScrip:OnCollisionEnter2D (UnityEngine.Collision2D) (at Assets/BirdScrip.cs:34)```
yes
1/100 is also 0 because it is integer division
but I'm incrementing it
I defined it as float tho
and yet 1 and 100 are both ints therefore 1/100 is 0
you need at least one float literal in your division for the result to be a float. so 1f/100, 1f/100f, or 1/100f would all work
idk why but when I assign 0.01 to a float variable it gives me compilation error I don't think this happened to me in other programming languages
0.01 is a double not a float. there are beginner c# courses pinned in this channel if you don't know the basics
fair enough
Hey today I get the challange in jr Programmer with persistence. Creating savefile and stuff like that. Is there a better tutorial or smht? I do the challange make all finish but dont understand how this System works. 3h and brain hurts only to save a best score und username from input field.
Maybe explain what specific things you don't understand
Bumping from yesterday, still haven't gotten this figured out :/
Not sure the background of the System. I mean copy paste from the course ok but how that Codes working?
Why would you copy and paste? Read through the course and it's code and understand it line by line. You're never gonna understand anything if you just copy paste.
Like static Instance stuff. Hard to explain. And See many games using dot save files or something. And on the course it's json files but json files are easy to manipulate outside the game?
I read the Codes and try reading Codes from other Students to understand the System
Need to see the context, but static instance probably refers to a singleton pattern. This is not specifically related to saving and loading, but understanding the pattern and syntax would help you understand the codebase as a whole.
Idk but later Missions on the pathway feels like unity Was lazy to explain that with more Samples or something... Idk before every chapter 3-8h and the save file stuff only a 30 min chapter. 
And what's wrong with that?
I guess they expect you to understand programming enough by that point. Or be able to research on your own stuff that you don't understand.
It was that. But have not the Code now because im in bath. 😅
I asked many stuff on Chat gpt but Limit cool down now
Here's your problem - you're being lazy about researching. You really need to get into the habit of doing it if you want to continue coding.
- Don't rely on chat gpt(or any other llm/ai). At least not as a beginner.
- Read through manuals and documentation of API that you don't understand or see for the first time.
- Make sure you have the basics right. That implies learning the syntax and the different C# keywords, like
static
What im doing now? 😮
Donno. Complaining?
I searched since hours for a better tutorial to understand it. I mean lazy guys skipped that maybe idk
What exactly were you searching for?
Don't rely on chatgpt because it is wrong just as often as it is right.
"searching for better tutorial" already smells like laziness to me
How persistence works
You mean how the data is saved?
So I should trying without the knowledge? Without any tutorial?
Yes
Persistence is just a concept. It means that you keep your data (between something).
Code-wise or internal works of the language?
It's cool the tutorial say Do this and this and you get this. But how the background System works idk
Search for serialization in C#. Not tied to Unity.
Alright
Basically, you want to understand how to transform an object into something that can persist between states. It goes beyond just saving a game.
No, you should take one tutorial and go through it. If you don't understand a concept or word in it, Google it, read the manual, documentation, ask in the community, but don't discard that tutorial as bad and don't look for a replacement.
For that you'll need to read the code.
Im asking the community... Right now
That's another habit you're gonna get used to. Once you start getting into more advanced topics, there's gonna be not manual or explanation. Only code of other people that implemented it and documentation.
You talked about JSON and how it can be "easily manipulated", but that's the wrong way to see things. You need to understand when JSON is used.
No you don't. You haven't asked a single specific question about the code.
All I see is complaints on how hard it is and stuff like that.
And it is in fact because you want to easily manipulate the data
Yeah idk something about json. Was not many explain. That save stuff in Text that I understand
Many tutorials use json because it makes it easier for you to see what's being saved
Break it down into small questions. Things you have difficulty understanding. And ask them in order. Don't just throw a "I don't know how the system works".
But either way, doesn't matter the format you use, data will be manipulated and poked at by the end user
Binary, json, xml
hi can someone help me understand my code wont shoot out the bullet for my Ai?
Yeah i looked inside the json try to understand which date He save how and from where
It's the wrong approach in how you are trying to understand. You basically asked "why json bad" instead of "why use json"
Yeah when im back on pc
Implying that the tutorial is wrong for using json, when json has many use cases
prettyprint
So, you didn't search about json
No I understand why use it in the tutorial in that case. But I only know json from Minecraft Server to open it with notepad++ and easy edit stuff. That's what I mean
json is a big ole' string
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections.Generic;
using UnityEngine;
public class AiShooter : MonoBehaviour
{
public GameObject Bullet;
//shot timings
private float timerShots;
public float timeBtwShots = 0.25f;
public float fireRadius = 25f;
public float Force = 2000f;
// Update is called once per frame
void Update()
{
float distance = Vector3.Distance(PlayerMove.playerPos, transform.position);
if (distance <= fireRadius)
{
AI_FireBullet();
}
}
void AI_FireBullet()
{
RaycastHit hitPlayer;
Ray playerPos = new Ray(transform.position, transform.forward);
if (Physics.SphereCast(playerPos, 0.25f, out hitPlayer, fireRadius))
{
Debug.Log("shooting");
if (timerShots <= 0 && hitPlayer.transform.tag == "Player")
{
GameObject BulletHolder;
BulletHolder = Instantiate(Bullet, transform.position, transform.rotation) as GameObject;
BulletHolder.transform.Rotate(Vector3.left * 90); //sometimes needed sometimes not
Rigidbody Temp_RigidBody;
Temp_RigidBody = BulletHolder.GetComponent<Rigidbody>();
Temp_RigidBody.AddForce(transform.forward * Force);
Destroy(BulletHolder, 2f);
timerShots = timeBtwShots;
}
else
{
timerShots -= Time.deltaTime;
}
}
}
}
(debug is working as well so it tech is "shooting")
And I'm telling you that you didn't search about jsons and its use cases and what it essentially does.
And why other games may use different formats
Which is not much of a you problem tbh
instead of only printing "shooting" you should print some useful info, like what was hit by the spherecast as well as the value of timerShots
im ngl i have no idea how to do that
there are beginner c# courses pinned in this channel if you don't know how to use the variables you already have . . .
I think it comes down with the fact that people who are starting with game dev don't really understand what data is, as they don't usually have a computer science background.
So there is not much understanding with what to do with data
And that's why you should always start with a general coding course
Instead of beginner game development ones
i mean if the debug is "shooting" dont that mean the raycast is working and hitting the Player only? no?
no, it just means the spherecast hit something
but its only meant to hit the object tagged with Player and only shows when that happens?
The debug is outside the if checking the player
im sorry if im not understanding properly
you're making assumptions. but clearly one of the two things i asked you to check is not what you expect. so verify that information instead of assuming it is working when it very clearly isn't
yes its verified that its hitting the player so what can i do now?
So, this part:
{
Debug.Log("shooting");```
Will print "shooting" when the cast hits *anything*.
how have you verified that?
You either move the log to the second if, or, as boxfriend suggested, print more useful information.
Either way, I believe the problem is that AddForce is so fast it ain't registering the collision.
Or, like, you are not even noticing it
2000f force is crazy
Debug.Log($"Shooting: Hit {hitPlayer.transform.name}, TimerShots: {timerShots}");
used this line of code
great! so what exactly did it print?
im using that force on my player one which works
I see
then you are absolutely using AddForce incorrectly in all places you use it
now print the tag of what was hit and make sure that is what you expect since you are using the tag for the condition
how would it be incorrect is there ONE correct way that everyone has to follow for it be correct?
I mean, how are you using the same amount of force for a bullet and the player?
Like, the problem is the quantity
thanks figured out the issue
you shouldn't be using deltaTime with your forces, you shouldn't be applying force in Update except for one-off forces using an Impulse forcemode (or the other 3d forcemode that is instantaneous), you should be using reasonable amounts of force, especially for objects that aren't fucking gigantic
i forgot to actually tag my player...
now do you see the value of printing actually useful information instead of random non sequitirs that don't actually convey anything?
Now I'm curious how the addforce 2k is working because that's, like, a lot
using System.Collections.Generic;
using UnityEngine;
public class FireObject : MonoBehaviour
{
public GameObject Bullet;
public float Force = 2000f;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
GameObject BulletHolder;
BulletHolder = Instantiate(Bullet, transform.position, transform.rotation) as GameObject;
BulletHolder.transform.Rotate(Vector3.left * 90); //depends on rotation of weaponholder
Rigidbody Temporay_RigidBody;
Temporay_RigidBody = BulletHolder.GetComponent<Rigidbody>();
Temporay_RigidBody.AddForce(transform.forward * Force);
Destroy(BulletHolder, 1f );
}
}
}
this is my character shooting but when i dont get the 2000 force it shoot but wont rlly go forward even now it doesnt go forward as much
they aren't using the right forcemode, so it's actually only applying a very small fraction of that amount of force
you shouldn't be applying force in Update except for one-off forces using an Impulse forcemode (or the other 3d forcemode that is instantaneous)
Yeah, it's because you should be using FixedUpdate
that's not why . . .
This too. Not only for the force, but also for the cast.
Hmm, then why?
then what how can i apply it for it to work still
one-off forces using an Impulse forcemode
Ah, I see
i feel like i'm taking crazy pills today with all this repeating myself i have to do
there is nothing wrong with it being in update
Hmm I dunno, when doing casts it can get really innacurate
never heard of impulse forcemodes is there i can follow/read?
Unless you are changing the position directly
it will be just as accurate as using FixedUpdate because it will be querying the exact same state of physics
literally just look at the documentation for AddForce
Are you sure?
I do use it sometimes when, like, doing a kinematic controller
But I usually use Translate
yes, the state of physics is updated on FixedUpdate frames. there are no extra physics updates between those that would cause any sort of "inaccuracy", it just might be visually inaccurate because one might assume that a raycast should hit when they are looking at an interpolated object
I was under a misconception then
so i change this
Temporay_RigidBody.AddForce(transform.forward * Force);
into this?
Temporay_RigidBody(0, 0, thrust, ForceMode.Impulse);
ty for sorting that out
of course these visual inaccuracies are really only going to be visible if you actually pause execution to look at the rays between physics updates since the time difference would typically be too short for someone to actually notice
sure, if you want to pass the extra parameters instead of just keeping what you already had
just make sure to reduce the amount of force by a lot
i appreciate the support! thanks
But the wrong force mode in the update still can cause problems, right? Like the default is applied in each fixedupdate frame
right, the only acceptable forcemodes to use in Update are the ones that add a one-off force (like Impulse) that won't accumulate over time like ForceMode.Force does
I see.
and this is really because they don't factor in deltaTime when applying the force and just apply it all at once. though if you plan to use it multiple times on the same object, it would be recommended to do it in FixedUpdate (or at least on a fixed timestep) rather than every frame
One thing I noticed when using AddForce (default mode)
Was that if I turned off gravity, it would make the object move forever even when limiting its velocity and stopping applying the force
I had to increase drag by a lot
(it moves forever but veeery slowly)
with no drag and no friction on the material that is the expected behavior. you have to have some sort of drag or opposing force to make it stop
Drag is applied opposite to the force, right?
So how can gravity work like drag for that when it is only applied down?
If moving to the side
for example
Anyways I think this is offtopic lol
sorry
Yesterday I saw a student creating a game and realising that the camera light, left a trail behind the moving shape. By chance, it gave a better 3D feel to the shape of the moving character.
Camera light ? what is the exact question ?
i think hes asking for a replication
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootingTrigger : MonoBehaviour
{
public PeaSpawner ps;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Zombie")
{
Debug.Log("Enemy in lane!", this);
this.ps.Shooting = (true);
}
}
void OnTriggerExit2D(Collider2D other)
{
Debug.Log("Enemy out of lane!", this);
this.ps.Shooting = (false);
}
}
so this script is working weird and the ontriggeerexit keeps hapening so i dont know dispite it not exiting
You only check the tag in Enter, which seems odd.
Also you should use CompareTag, not equality
ok
How would i do it?
ping back
do for exit or enter?
It's your logic man, I'm just saying the above.
do you want to see a video for a better visual understanding?
No
ok
You have a problem, you received sufficient help for it, that means you have to implement the tips you received on your own
i set the collision detecting to continus
For a better explanation when shooting is true, it spawns a prefab every 1.5 seconds, and when the prefab spawns the shooting variable seems to get turned off
IT WORKED
I TRIED IT!
which version of calculating the b vector would be more efficient? whats the best way for a new programmer to know what would be more or less costly? this is going to be run by a lot of Segments at the same time so i need it to be as efficient as possible
There's not gonna be much difference if at all.
A word of advice: don't get into micro optimizations before you have an actual issue.
As for how you can tell which one is faster, you should benchmark/profile both cases and compare the metrics.
I'm realizing as I start this new project is probably not a great way to do it. I'm trying to find some sort of code that can allow players to place their own tubes and wires anywhere they want in space, then have it calculate how many 'segments' of tube/wire are needed to complete this to get a cost for the total amount and to calculate how it should lay across the ground when placed
I'm trying to think of a better way to design it, but I want players to have full control over where pipes/tubes/wires are in the play araea
If it's an expensive operation, you should consider offsetting it to jobs/background threads or a compute shader. Or spread it over several frames.
As for the actual implementation, there's not much I can say, as I don't know how you have it setup right now.
Sorry,... that was a random comment. I was reading the previous comments regarding gravity and remembered the light effect following this game character.
I'll explain it better after asking the student how was he dealing with gravity, that causes this "light teail" effect.
Cheers.
Is there a way to do a "cone" cast?
No, casting only works with primitive shapes.
Either calculate the angle of nearby objects or create a mesh and use a mesh collider on it
In that case, do you have some advice when trying to achieve something like this?
dot product prob
I'm trying to make a selection system that's cone\frumstrum shaped
and selectables closer to the direct forward vector from the controller have priority selection
You could probably do raycasts in cone shape then compare angles / dot product on each one hit. give whatever thresholds you need
If i had a wide angle cone, wouldn't i have to cast maybe hundreds of raycast for accuracy?
how wide? I use one for mine that goes up to 270, that has about a hundred or two and its fine
also depends how big colliders you plan on hitting are
you don't technically need that , you just need a way to grab whats infront of you. Overlap and Spherecast could also work, with ray / lines is just easier to account for narrow angle / hits from the origin point
why is it when i code and then save it, when i go back to unity editor it says completing domain or something, how do i turn it off?
because it has to reload / compile the entire assembly each time
You can toggle it of in the preferences iirc
Why would you want to do that?
I might give that a try, but it feels like there might be a simpler way
if i toggle it off then everything would still work the same right?
I suppose not
just grab whats infront of you and compare angles. idk how much simpler than that you want lol
since that's the process of actually getting your code in the engine
you would have to manually reload if you want changs to eventually reflect what you saved
i guess you could that manually
oh
damn
your code has to be turned into machine code
i mean i save frequently when i write code so it is such a hassle waiting for that popup to finsh
if you save frequenetly and are coding in IDE, why even go back to the Unity Editor, I just stay in IDE until I need to link stuff in inspector n setup
its nt like it blocks IDE when it does that compiling
Hello all, i am trying to capture a photo from the player's device (mobile, front camera) and save it as a png. I have been searching through the documentation and haven't been able to understand. Can somebody help me through this? Thanks!
is there a way to cancel the Invoke() fucntion from happening once you call it
thanks! I will check this out
only invoke repeating iirc, you could either use a coroutine or async function you would be able to interrupt/cancel it
okay thanks
how would i check if the gameobject has a tag x
have you tried googling this exact question?
i did, and i found out how
You mean like CancelInvoke?
im not using InvokeReapeating so i dont think that'll work
Hi everyone! I am still new but I know unity is having a Black Friday sale. Anything that is useful that I should have. Thank you!
Why do you think that
Hi, this is a coding channel. I suggest you ask this in #💻┃unity-talk
(Even questions about nice coding libraries 😄)
Sorry I thought this was unity talk channel I must of changed it without noticing. Thank you!
doesnt CancelInvote only work with InvokeRepeating
Again, why do you think that?
Check the docs https://docs.unity3d.com/ScriptReference/MonoBehaviour.CancelInvoke.html
Cancels all Invoke calls on this MonoBehaviour.
Sounds straightforward to me
It should also work with InvokeRepeating though
Note that Invoke is a bit of a dated way of doing this stuff so coroutines/async/awaitables are an option
oh i just saw InvokeRepeating in the example and just assimed in wouldnt work with Invoke
I see, well, try it
EasyVector Lerping
Hello Guys!
im following a Toturial and there is a Problem.
as you know FindObjectsOfType has been depricated and the other methods dont get an argument or cant be used this way.
any idea how to fix this?
cs IEnumerable<IDataPersistence> dataPersistences = FindObjectsOfType<MonoBehaviour>().OfType<IDataPersistence>();
Hey Guys, I'm trying to figure out why my jump is not working for my 3rd person jump code. Could someone help me out? Can I paste my code here?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
please do provide more info about how exactly it isn't working
I'm currently getting a NaN on my jump velocity Vector3 whenever I press space, resulting in the character freezing wherever they are. I'm very new to this and I tried combining brackey's 3rd person movement tutorial with his jump from his first person movement tutorial but the math confuses me.
https://hastebin.com/share/jogudimohu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Look at the doc and see if there's a replacement:
https://docs.unity3d.com/ScriptReference/Object.html
The doc of FindObjectsOfType also tells you what you should use instead
what's with Mathf.Sqrt(velocity.y * -9.81f * gravity);?
that doesn't really make sense
both hardcoding gravity and using a variable? using the existing y velocity?
it's how Brackeys suggested to implement the jump function. For me it didn't make much sense either but I gave him the benefit of the doubt
I'm open to better ideas to implement jump
i have read the doc but the suggestions dont take 0 argument.
thats the problem.
I tried using RigidBody but I think it doesnt go well with the characterController as it stays grounded.
This is the replacement
set the y velocity to a specified jump velocity, or apply a vertical force with aspecified jump force
Instead of the generic it takes the type as a parameter
And also it has a sort. If you don't care about it just pass none
Give it the argument then
If thats what you mean
Tell it if you want to find inactive objects or not
ThankYou! 🙏
Thank You!🌹
are you sure this is exactly what was suggested? there's no part of this that makes sense
The NaN probably comes from giving negative input to Mathf.Sqrt
And yeah that line seems really weird
for some reason unity wont show any settings in the components tab for player movement, im following a tutorial and im pretty sure i didnt make any mistakes (sorry for the text wall)
public class PlayerMovement : MonoBehaviour
{
private CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f * 2;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.04f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
bool isMoving;
private Vector3 lastPosition = new Vector3(0f,0f,0f);
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
//Verifica se o jogador esta pousado no chão
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
//Aumenta a velocidade quando o jogador salta
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
//Criar o vector de movimento
Vector3 move = transform.right * x + transform.forward * z;
//Movimentação do jogador
controller.Move(move * speed * Time.deltaTime);
//Verificar se o jogador pode saltar
if (Input.GetButtonDown("Jump") && isGrounded)
//Jogador salta
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
//Jogador cai
velocity.y += gravity * Time.deltaTime;
//Jogador executa o salto
controller.Move(velocity * Time.deltaTime);
if (lastPosition != gameObject.transform.position && isGrounded == true)
{
isMoving = true;
//Poderá ser usado mais tarde
}
else
{
isMoving= false;
//Poderá ser usado mais tarde
}
lastPosition = gameObject.transform.position;
}
}```
that would help alot with finding out why you are getting NaN if you tell the string where this error appear
You need to fix all errors first so the script compile and display serialized fields.
alright let me check
I dont get what this means, i double checked and its the same as it is in the tutorial
Vector3 move = transform.right * x + transform.forward * z;
Is the previous line also the same as in the tutorial?
yup, the only difference there is the comment
No the actual previous line, ignoring comments
Configure the !ide so that it'll tell you when this kind of thing happens 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
alright, thanks!
Hello Everyone!
So I’m currently learning the Unity Game Engine by doing the Unity Pathways courses, it’s been a very fun process and I’m really enjoying applying all of the previous programming knowledge I’ve had in the Game Dev context. I’m currently working on my Personal Project assigned in the Junior Programmer course. I’ve decided to try and create a simple wave based 3d top down shooter, I thought this was a simple idea but it turned out to be a bit more complex than what I thought, especially in the collision department.
So I’ve currently got the Basic Gameplay down, the player can move in all directions, shoot projectiles and i’ve also added a neat little Dash mechanic to it. I’ve also added a couple of enemies that can also shoot projectiles at the player and follow him. The main problem I’m having now is that I’m using Trigger Colliders to run the code I want for the interactions between playerprojectile/enemy and vice-versa, this then makes it so the player gameobject won’t collide with the enemy gameobject’s and they’ll phase through eachother and i’ve been trying to find a way to make it so this won’t happen. After some research I think I’ll have to use the Unity Layers System to fix this but I’ve been having a hard time understanding how it works and how to apply it to my project.
Hope somebody can help and thanks in advance 🙂
Is there something stopping you from having non-trigger colliders on your player and enemies?
Well the way I programmed the projectile collisions from player to enemy and enemy to player uses trigger colliders. It was the most logical and natural way to do it for me, and I was also having some issues when using normal colliders instead of trigger colliders, where the projectiles just wouldn't work how I wanted.
You can still use a trigger collider on your projectiles
Just switch the player and enemy colliders to non-trigger ones
And damage them through the projectiles OnTriggerEnter
Bruh I thought they all had to be trigger colliders for it to work ;--;
Thanks for the help haha
btw, you do know you can have trigger and non-trigger colliders on the same object
Yeah that's what I was gonna try to do. To have a non trigger to read the collision with other objects and one for the triggers. But I was clearly just not understanding how the trigger colliders work haha
Here's a nice matrix showing how things can be paired in order to receive a trigger message
https://unity.huh.how/physics-messages/trigger-matrix-3d
Thank you very much!
This is a code channel and your question isn’t code related. Delete it from here and ask in the correct channel-> #📲┃ui-ux
whoops
Hello, Im learning unity.
I want to know what is the equivalent of this code "OnTriggerEnter2D(Collider2D other)" but for 3d. Or is it the same but just change 2D to 3D ?
just remove the 2D. Referring to the Unity documentation would have given you the answer in < 2 seconds
Thanks ! This gave me an answer in 1min tho
next time docs first, ask after
you'll never know if you don't debug your code
right.. okay
this is all that is showing. I put debugs in the main shooting mechanisms.
So why not put Debugs at the START of each method to see if it is being called?
Consider following the steps explained here: https://unity.huh.how/physics-messages
That is, if you debugged up until the point where the issue is related to the collission not triggering
Hello,
I want to take the collider to put it in my CinemachineConfiner every time I switched scenes. Is it better that put it in the OnSceneLoaded or in the Awake() ? will there be any change ?
using Cinemachine;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SetCameraLimitation : MonoBehaviour
{
private void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
if(scene.name == "_preload")
{
return;
}
//CompositeCollider2D affecter à la caméra
CinemachineConfiner2D confiner2D = GetComponent<CinemachineConfiner2D>();
confiner2D.m_BoundingShape2D = SingletonManager.instance.cameraLimitation;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
}
im afraid it might be my takedamage method
how can it be your TakeDamage method if that is never being called?
like i said, it might be. thats what i'm thinking as of right now. it might be in my OnCollisionEnter method, but everything looks fine there
well it didn't look like you added debugging there to make sure it is firing
im actually so dumb the bullet didnt even have the bullet script attached 🤦♂️ so sorry for wasting your time
First rule of debugging. Never assume ANYTHING.; Second rule of debugging. Check EVERYTHING
i realize that now, sorry for wasting your time
How do I reorder objects found by FindObjectsWithTag?
They're randomly ordered for some reason
you sort them the same way you would sort any array
there is no guaranteed ordering. don't use any of the Find methods if you need a specific object. get a proper reference to the object you want to use
Oh I meant objects*
There's multiple
then just sort the returned array like you would any other array
how.
literally just google "sort array c#" and find out
ok.
I now have a problem with this Issue
||At least one object must implement Icomparable||
My code is here:
Array.Sort(Lamps);
Did you actually bother going and reading any documentation on this?
you need to implement IComparer
remember when i said to google "sort array c#" and not "sort array unity"?
Great, try reading that
🙂
Hi I need help. I have 2 difference textures and I need to reference the texture from another script and load it into button. Why is it not working this way?
nothing there loads a texture into a button
sorry I'm dumb
This code goes through the list inputList and if a value is greater than the latest value in the stack substack , it moves the value from the list to the stack. I'm just curious if either of these two methods, the while or foreach loop, is at all more efficient than the other:
while(i < inputList.Count)
{
if (inputList[i] > substack.Peek())
{
substack.Push(inputList[i]);
inputList.RemoveAt(i);
}
else i++;
}
foreach (Sphere sp in inputList)
{
if (sp >= substack.Peek())
{
substack.Push(sp);
inputList.Remove(sp);
}
}```
you cannot remove in a foreach
Why not? Is it the same problem as if you try to use a for loop?
no. you cannot modify a collection you are iterating over with foreach
Oh I see, thanks
btw, neither will work, both will throw exceptions
does anyone know how to constrain a player's movement to a spline? so i can click somewhere on the screen, it takes the x value, and moves to the nearest point on the spline?
trying to use this but can't figure it out
that's because the Evaluate method doesn't do that
how would i do it then?
that would depend on the spline, you could walk it or binary chop it
how do you mean, and what about the spline does it depend on?
the shape, binary chop would not work on a spline which is very curved
could you elaborate? these terms are not familiar to me
walking the spline means starting at t=0 and then looping until t=1 evaluating the position as you go and saving the one you want.
binary chopping the spline is starting in the middle and moving up or down by 50% of the remaining length until you find the position you want
Hello, I was trying to smoothly rotate my FPS camera using Mathf.SmoothDampAngle function to fix the little jittering happening when rotating my camera on a FPS controller. I have been trying to implement it for some time and I can't figure out how am I supposed to do it this way or another?
This is the base code in the update function
private float rotationX;
rotationX -= modifiedDelta.y;
rotationX = Mathf.Clamp(rotationX, minY, maxY);
camera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0f);
transform.rotation *= Quaternion.Euler(0, modifiedDelta.x, 0);```
Generally factoring deltatime into mouse rotation in any capacity isn't a good idea
Certainly multiplying the mouse input directly with deltatime is wrong
Mouse delta is already framerate independent, since it's telling you the actual mouse delta for this frame
Would you rather do x == null or x is null?
second is not going to work correctly with types that derive from UnityEngine.Object, you have to use the == operator with those because otherwise they will throw an exception if they are "null" (ie destroyed) but the variable hasn't been explicitly assigned null because unity has overridden the == operator to check for destroyed objects but it is not possible to override the is operator to do that
Ok that makes a lot of sense, thank you for the very detailed answer 🙏🏻
yeah in the case of regular C# the "is" one is fine but anything involving UnityEngine.Object derived stuff yeah make sure you are hitting the equality operator
same goes for ?. and ?? which also skip it so should not be used on UnityEngine.Object stuff
So let's say I do
GameObject g;
g?.Method()
would not work since GameObject inherits from UnityEngine.Object
correct
same for scriptable objects, and all component types
there are many cases where as far as the engine is concerned a object is destroyed but to C# its not null
checking via the equality operator lets unity use its own logic here instead of doing a real null check
its one of the larger gotcha's of unity, seen it hit newbies and experienced programmers hard too
and it's always fun when you're working with interfaces and end up checking a MonoBehaviour for null...
Actually that's exactly how it works in ROBLOX as well. The variable itself isn't dereferenced, yet the instance pointed by it had Destroy() called on itself, which makes it internally unusable. Hence why non-overloaded operators won't behave properly
in unity its a combo of how GC works, and how there is a C# side and a native side to the engine
Here it's more noticeable definitely
This would work fine it just wouldn't detect if you had destroyed the object in between those two lines
I.e. it would still call the method on a destroyed object
i was not going to split hairs on that one, generally best practice is to always use equality operator on UnityEngine.Object
but yeah the case given would work since its real null since its never been given a value
Yes, and this isn't specifically something you'd want to do since it kind of proves you are either not caring about such case, or that you don't really know what's going on
In ROBLOX you would get somewhat yelled at depending on what you want to do. You can still modify most of the properties of the implicit object for sure, no error whatsoever
you can see the difference in the reported exception as well
NullReferenceException vs MissingReferenceException
Gotcha, thanks a lot as well for your time
the somewhat related gotcha around this, is how Destroy works as well
it does not do the work immediately, but does it end of frame
I'm trying to make a sprite walk, and i'm getting "identifier expected" error (and if there's a way to differentiate between pressing, and holding a key please inform me
{
if (Input.GetKeyDown(KeyCode.RightArrow) == true)
{
myrigidbody.Velocity = Vector1.(1,0);
}
make sure that your !IDE is configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
I just got it installed, i had visual studio, not visual studio code, it's so much better already
thank you
visual studio is the better one. vs code is the worse one
you just need to configure it
like this?
that is one step of it, yes
why can i make something that when my code is started is equal to null but then if i try to set it equal to null during runtime it doesnt work right
Show how you're doing it, the only thing required is to do v = null; - if it still has a value afterwards, something else is re-assigning a new value into the variable
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You log target right before setting a new value into it, you should log right after so you get an up-to-date value displayed in the console
Also log inside both OnTrigger* methods, make sure you don't enter the trigger right after exiting it
thank you so much for your help
it turns out im just an idiot
and didnt set the script that EnemyMovement was supposed to look in for the check_target() return statement
so the Null exception error was from there being no script for the code to get check_target() from
You had an exception? Should have mentioned that in the first place
But glad it's fixed
Does anyone know why some of the "enemies" are sometimes being destroyed even when they are far from the collider? And this only happens when the "sword" is active, the script is simple just to make the rectangle rotate around a gameobject
GetKey looks every frame for a continuous press (Hold), GetKeyDown is active once when the specified key is pressed, GetKeyUp is active once when the specified key is released.
Can you show the piece of code that checks for collision/trigger between the enemy and the sword?
Also Vector1 is kinda suspicious 🤔
Should be on a script either on the enemy or the sword
Thank you!
Also looking in the documentation can help a lot for little things like this, !docs
Of course, here go
Ohhh hang on I see what's happening :)
The enemies get destroyed when they collide with anything, not just the sword. Including another enemy
At the start of the video a pair of enemies top left touch eachother and get destroyed
Oh how I didn't realize this was happening before xd
I found the mistake, lol thanks very much ❤️
How do I create a Serialized Field that I can use to say "This is the next scene I want to load"?
Build Index feels absolutely dirty and error prone (however I can work around this if it is truly the only way by means of a GameConstants.cs file).
Thanks, I will look into this!
NaughtyAttributes also has an attribute for that to slap on an int or string variable and draws a dropdown to select a scene
https://dbrizov.github.io/na-docs/attributes/drawer_attributes/scene.html
Interesting.
Im using the new input system. How do I make a button only fire when in the frame which it is pressed. Seems like whatever settings I use I get continuous presses.
Hi. I used "button" action type for this. In input configuration.
Yes but if I hold the button every frame I get acknowledgement that the key is held. I want it so it fires once from when I first press it
To get around that, I added a "intervalBetweenButtonPresses" variable.
if (button is pressed and intervalBetweenButtonPresses is <= 0)
{
do this action
intervalBetweenButtonPresses = 1f
}```
This way the button action will only occur once a second.
If there's a better way, I'd like to know.
Is it a demerit to use gpt chat to help you make some scripts for your game?
I wouldn't trust any code chatgpt gives you.
it will do you more harm than good
The started event just worked for me there is your better way 🙂
my apologies thanks for the help!
best you learn how to code in C# and use unitys API #💻┃unity-talk message.
For touch screen I've added binding for Press. It triggers only once for me.
I'm going to read what navarone posted.
yes
boilerplate can be acceptable if you give precise instructions & can verify the validity
you can subscribe to specific callbacks or use the triggered property . . .
A stray projectile which may be a tomato will fly in your general direction if you use chatgpt for writing you code
I learned Java the hard way, but I confess that sometimes I'm too lazy to read the Unity documentation and I ask for tips on how to do some things in the GPT chat.
the main problem with that is, usually give you something that's inefficient, convoluted or just plain wrong
Yeah thats true
i use copilot/gemini for my codebase. it's great for documentation . . .
Hey, i'm thinking of making my player a state machine, and I was wondering what parts of it are needed to be in different states? Is it just movement that should be tied down to different states like grounded, swimming, airborn, etc. or should i have an attacking, rolling, interacting state, etc as well?
hi y'all, I am totally a newbie on all this, but I am unable to program some text display. I would like to make an app that has a HUD like in terminator or robocop (very simple HUD with just text)
it is for a Meta Quest 3. I was able to make an app that displays just a cube, but I am unable to make something that would display text that remains in the FOV
my bool array in my inspector and during playtime are different even though they're the exact same array. my array only saves/loads with the values i put it in it during playtime. why is this?
scripts that modify/save my bool array
https://hatebin.com/dfhulcojaq
https://hatebin.com/cqrvbtjifb
https://hatebin.com/dhrhbqtzqp
the 2nd link are just random scripts. where is the GameManager class?
here is my GameManager class
https://hatebin.com/lckqydkjbm
check what assigns or overwrites flags. log those values. it's probably an empty array . . .
but the problem is im not really sure whats changing the flags array, it's not empty because if i add for example 2 elements to it at runtime then exit play mode and play again then it will now have 2 elements
then you need to look in your code where flags is used to check when the value is changed; then you can log/check the values from there . . .
hi, i've figured out that in this script, it debugs the inspector size of the array where ive commented.
https://hatebin.com/tykhimtyik
so it seems like that the Flags from PlayerData is a different value from flags and overrides it (right here: https://hatebin.com/libszevvat). is there way to reset both of both of these arrays and then set them to each other? i think the core of this problem arose when i was testing both of these arrays and did a few runtime shenanigans on Flags which caused it to override the GameManager.flags array
NVM ITS SOLVED NOW. thank you for your help!! ^ ^
I'm not sure if this is the right channel, but is it possible to save assets you made in unity for example, sprites?
I forgot to mention during runtime.
Did you search how to do that?
Yes. You can save them in the editor, but not during runtime. I only ask because I'm making art software in unity.
Unity 6 has entire class dedicated to conversion to different formats, it's in the manual.
ImageConversion
I'm also using it as a video editor.
Might as well reply.
This is the reply. You just need to go through the effort of looking it up in the manual where you find all the usage examples.
It even has an example of how to use IO library to write to file right there.
Guys I have an object I want it to go to a defined position parabolically how can I do that ive been trying for 4 days i can't do kt
You'll need to decide what way you want that parabola to bend. There can be an infinite number of parabolas between 2 points in 3d space.
Actually 2d 😅
Yes bend
In 2d too
