#archived-code-general
1 messages · Page 337 of 1
Also make sure you read my previous message. Use GetKeyDown for optimization
Perfect
It would work even better, had you read the 2 previous messages from me
Though use comparetag
True, use input.getkeydown
i did
Lol
ok
Collider is derived from Component
Make sure you know that gameObject reference is not required
other.CompareTag("BoxCenter")
Component.CompareTag
Also make sure you have a method for checking the tag and assigning the boolean to not repeat the same code twice
private void SetTrigger(bool value)
{
if (other.CompareTag("BoxCenter"))
InsideTrigger = value;
}
Howw 😭
Shown above
There is no way I'm letting you use CompareTag("BoxCenter") more than once 😉
right?
No, the if condition can be used without the brackets if there is just a single line inside of it
Cleanest code out there
Like this right?
Sorry, forgot the 1st parameter
The Collider collider should be added as the 1st parameter
private void SetTrigger(Collider collider, bool value)
{
if (collider.CompareTag("BoxCenter"))
InsideTrigger = value;
}
how do i use it now?
So you call the method
And inside the parentheses you put the variables or values, and because there are 2 parameters you separate each "value" with a comma
If I take scripts from youtube tutorials and use them for my own projects, is that legal and fine?
Check for a license listed anywhere in the video, description, or any page where the source code is posted
above message ( #archived-code-general message ) and also if theyre making a youtube tutorial on it and they have the script as open source and they also have the script in the video then most likely yes
Assuming it is their script :D
Okay, thank you
yea
Lol, some youtube "tutorials" on unity don't even know basic c# and purely use visual scripting lmao
guys whıch unıty versıon you prefers? For good performance.
but same time the version should be have some ımportant updates or somethıng
The most recent LTS
ı downloaded 2022.3.33f1
but ı want a good performance versıon
because ı open other programs background and sometımes unıty took some much tıme
yea that ıs my mıstake
@heady iris you thınk whıch channel good for talk about somethıng lıke that?
ı dont know much thıs server
#💻┃unity-talk would be appropriate (but i don't think there's much of an answer for your question)
Boys I have a new hyper fixation. Animations systems in card games. How do they work? I assume animations are added to a queue and executed in order?
Each item in the queue is some type of AnimationHandler that manages the movement and coordination of specific objects/effects?
oh okay ty
I guess? These types of animations typically have quite a bit to coordinate beyond tweens.
With the meta shift of the OTA patch Phoenix Force is finally playable again! This combo deck requires patience similar to a mister negative deck, but it hits much more often. This sneaky deck can always pressure the opponents, but keep an eye out for counters like Shadow King, Cosmo, or Killmonger that stop you from hitting your high role play....
Marvel Snap is a good reference for this.
I usually reference slay the spire and I can tell you that game interupts everything
Ya Slay the Spire barely slows down and just vrooms.
that game does seem like it has a bunch of animations when a card is played, so yeah that'll probably need a pause between what's played
I was more talking in the general sense of how you move the cards around the screen and how your hand re-adjust when removing/adding cards to it
So ya, I imagine I’ll need some type of animation handlers thrown into a queue.
Maybe have them be mono behaviours and spawn them in as needed?
So they bring in the resources they need.
Like a movement anim could bring in the spline.
could just do a prefab route and have all of it on the gameobject
then call some Play() method that's custom to the prefab
assuming that each card has a different amount of components
Nah I think it’s better to be dynamic with this. Any card can perform any effect/animation.
Up to the handler to make sure it has the resources required.
i usually either go a large prefab variance, or a single prefab of components (which is populated by SOs)
Seems rough for hundreds of cards?
single prefab idea could incorporate every type of component... you just wouldn't use the components if the blueprint doesn't include it
at minimum you have some mesh/sprite, text, and a particle system as to what I'm seeing from that video
though you can't really just swap out particle systems like that unless you make some sort of manager system instead... but I like to overly optimize my stuff so instantiating components is always fine, especially in something like a card game anyway
vfx graph would however allow you to do that
Ya but there’s a ton of extra stuff crammed in some of these effects. Post processing changes, camera shake, all needing to be timed and coordinated.
You'd absolutely want something "pluggable"
so that it's easy to make lots of cards trigger the same camera shake
ya it's interesting
need lots of composable elements that execute at specific times
maybe it's finally time for Unity Timeline.
I'm wondering what the structure is here
like a card might have some "effect asset" id
that maps to some AnimationHander prefab
gets instantiated, loaded into the queue, and then executes its sequences when it gets to it
cleans itself up when done
well do you plan on ever having more than 64 items? Also do you plan to store literally nothing like a title or description? Unlockable states sounds like something that might grow, quickly. I really wouldnt be too concerned about the space of storing them in memory at runtime. This is just gonna make it harder. You'll also need some mapping from index to the title/description which means you're storing the data anyways but now theres just a bitmask too.
the only thing it'd really do here is replace having a bool on each instance of an achievement like
public class AchievementData
{
string title, description;
bool isUnlocked;
}
because you would be storing if its unlocked or not in that bitmask
and even then, you still need a mapping from achievement to index in the bitmask so im not sure if it would be better
some database support blob, you can store a bitvector
you can store as this
public struct Achievement{
}
Achievement[] achievements;
YourBitVector unlockeds;
ofc the length must be same
yes since you need to load the whole bitvector even if you want to query one archievement only
or check how your database store single bit/boolean value, i guess they have optimized it by compressing the data, then you can convert the true/false value to bit or store it directly
Question- Why isn't this working? It sets the rotation to 90 (Down, for some reason the camera is flipped?) when it goes at or above 0 degrees, and it doesn't even work for the -90
This is supposed to clamp the camera to -90 and 90 degrees
Astro_MainCamera.transform.eulerAngles = new Vector3(Mathf.Clamp(Astro_MainCamera.transform.eulerAngles.x, -90, 90), Astro_MainCamera.transform.eulerAngles.y, Astro_MainCamera.transform.eulerAngles.z);
I also noticed that the camer in unity is... inverted? -90 is instead 90, and vice versa for some reason
Is there some method for getting a transformation matrix chain from parent transform? Just like unity object to world works, the same principle but from object to target transform
That works automatically and doesn't multiply the whole chain each update
The code probably doesn't work as you expect, since one rotation could be represented multiple ways with Euler angles and there's no guarantee it's gonna be the same every time, so you clamping might be messing it up. You should cache your Euler rotation or specific axis angle and set it instead of reassigning the transform rotation in Euler angles.
is this a common issue?
the character in the animator is sinking in a weird swim-looking pose
That's the default avatar pose in unity.
This question is not code related though.
#🔎┃find-a-channel
GetKeyDown returns true only for the very first frame you hold down the key. GetKey returns true for as long as you hold the key
GetKeyDown would be for "Press E to interact" and GetKey would be for "Hold E to interact"
When marking a script with ExecuteAlways attribute, how would I go about making a variable persistent, so having its value not reset when changing the game mode from play to edit, without serializing it in the Inspector?
The thing is that the variable is a List, so storing its every item in EditorPrefs doesn't seem accurate enough
If it's for an Editor script, probably have an SO maintain the variable. Else reading and writing from disk is quite persistent - not too often, hopefully.
So you're saying that having a ScriptableObject as a wrapper for a List would be a great option?
Serializing it is the way. So the "without serializing it" restriction is odd.
The restriction was implemented to prevent the variable from being unintentionally modified. Seems like I can still serialize it and prevent any modifications using OnValidate
Or just hide it from the inspector with [HideInInspector]
This way the variable won't be persistent
[HideInInspector] does nothing to serializaiton
Sure it will, it's still serialized as long as it's public or has [SerializeField]
I see, it's not NonSerialized. Got it, thanks
Hey guys, I'm startng learning Netcode for GameObject from the documentation. So, I went to install it on my project it automatically installs version 1.9 while I was reading the documentation of the version 2.0.
The question is: Which version should I use during my learning journey?
and Which one should I use when building a game?
2.0 is for Unity 6 Preview
also, it's actually 2.0.0-exp
so it's an experimental version right now
but then again, the docs suggest that they're no longer maintaining 1.x
i don't have a good answer 😅
They should be reasonably similar
If you're using an editor version that installed 1.9.1 automatically, then just go with that
Alright I'll stick with 1.9.1 then
please do not cross post
Hey, I dont know how to fix the No Autocompletion problem, I watched almost all the YT Videos and followed all the steps, i even tried reinstalling Visual Studio 2022 but nothin helps. Any other uncommon ways to fix it?
!ide
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
• Other/None
Did you install the workload?
Did you set vs 2022 to the external tool?
Have you clicked regenerate project files after doing the above?
Also Reload with Dependencies in Solution Explorer of VS
Yes, tried all those steps multiple times
Including what steve said?
Show external tools
How does thet work?
You right click the solution, and click the option
Klick select Dependecies?
No
You do this in VS, through the solution explorer, as Steve said
Not in Unity
And you click a solution, not a script
Oh, thanks, that seemed to work.
Do you know, what I have to do, so that it opens this, when I klick on a script in unity?
if you have actually followed all of the steps of the configuration guide then visual studio will be opened when you try to open a script in unity
Select it in external tools
I asked to see that earlier
also clicked regenerate
Clicking a script in unity should open visual studio 2022
Yes, visual studio opens, but like the wrong way i think, because the MonoBehaviour is gray
is this not a screenshot of it working
What did you click reload dependencies in?
Click it in that file you JUST sent a screenshot of
Used a SmoothDamp to make crouching transition smoother, and it works fine on almsot everything, except when I am standing up while not moving.
!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.
Thank you, just had a little problem finding the setting / finding out what that translates to in germen.
I'd like some input on what would be a good way to implement intractability in my game
currently I have an IInteractable interface, with an "Interact" method
Issue is, there are some functionalities that could be shared by multiple different interactable objects - for example, making these objects produce sound upon interaction, or play an animation
Currently, I'd have to create separate fields for the audio and audio source on each different script that inherits from IInteractable, which isn't ideal
I thought about creating a InteractableBaseClass but to my understanding it's not the greatest practice because it's not very extendable
All the solutions I found online didn't take into account the extendability of the solutions they provided - they showed the simplest solutions (which aren't very extendable as the project grows in size)
Thank you in advance!
You can use events (UnityEvent to configure it in the inspector, or just plain events in C#) to add behaviors
For example, here's what happens when you interact with a lever
it tells a RotateMover component to start moving, a SoundMaker component to emit a sound (and generate a noise event for the detection system), and itself to turn off
Ohh I didn't think about that!
I could make that unity event a field on an interface?
more specifically the unity event haha
I just have one big Interactable component -- it's actually just a module that I attach to an Entity in my game
The UnityEvent would not be part of the interface
Interfaces are not rendered in the inspector anyway
The interface describes only the public behavior of something
oh, you mean manually implementing it in each class that inherits from the interface?
The fact that calling the Interact() method happens to invoke a UnityEvent is irrelevant
Right. And you might not even have that many classes, either
Fair enough, one line of repeated code really isn't a problem
Once you extract the consequences of the interaction out of the Interactable component, you don't have to create a new class to add a new feature
just watch me forget to invoke the event on each class lol
you only need multiple classes if you have multiple fundamentally different kinds of interaction
what would you class as fundamentally different?
well, the most basic idea would be that you push a button, your character plays an animation, and the interaction is completed
but maybe you could have interactions that you have to hold for a while, or interactions that pull up a minigame
some interactions I have are:
picking up objects
inserting them into machines
opening doors
I have a seperate script (class) for each interaction
is there a better way of doing doing these things to avoid having a ton of classes, or is it unavoidable?
Yeah, those are pretty distinct ideas.
A base class that provides the UnityEvent would be reasonable
hmm how do you use the unityevents though? for example, if you want to add sound, do you add an audio script to the object, assign a clip and then set the unityevent to play the sound?
or do you have a central audio manager and you somehow pass the audio clip with the unity event?
I see, thank you so much for the help, I seriously appericiate it!
The idea is to use small components to add individual features
rather than trying to mash all of your features into single components
Yeah I don't know why I struggle with doing that so much
hello,
for some reason I get:
Coroutine 'ResetJump' couldn't be started!
when trying to start a coroutine from a non-monobehaviour.
weird because starting one worked many times in the past.
What I do is get a reference to a MonoBehaviour, and do myMonoBehaviour.StartCoroutine("MyChildClassCouroutine");
here is the executing code on the non-MonoBehaviour:
controller.StartCoroutine("ResetJump");
and your ResetJump method signature is?
public IEnumerator ResetJump()
{
yield return new WaitForSeconds(0.5f);
isJumping = false;
}
Is ResetJump on the monobehaviour script or this script?
why start it with a string and not ResetJump()
this works, thanks
odd because Invoke also gave the same error and it didn't work when I tried this way or as a string
why not just call a public method that Starts a private IEnumerator 🤔
I wouldn't do that lol, too many functions for a simple Invoke
ehh I never make my Coroutines public
always start them from their containing class
public void ResetJump() => StartCoroutine(ReseJumpRoutine());
private IEnumerator ReseJumpRoutine()
{
yield return new WaitForSeconds(0.5f);
isJumping = false;
}```
If you pass a name, Unity looks for a method with that name on the target MonoBehaviour
It doesn't look for a method with that name from the class that's calling StartCoroutine
that would be weird
Hi im getting an error that says 'Object at index 0 is null' is there a way to fix this
here is the code
!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.
that makes very much sense, thank you
!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.
you are meant to like read it my friend..not just blindly copy
private void Start()
{
fpc = GetComponent<FirstPersonController>();
}```
Does anyone know why i get a Type Mismatch when a try to add a fpc in the editor? ctrl + click goes to the right class
I am using the modular first person controller from Jess Case
what happens if you assign it in the inspector and not in the Start() method?
it says type mismatch
presumably because you have multiple different FirstPersonController scripts in different namespaces
is there a way to specify which fpc im using in the script?
yes, by preceding it with the namespece or adding a using statement for the namespace
Why does it matter that it takes less time to implement the graphics than making them?
It's most often the case
Well the obvious answer is to practice and get better
Or use AI and then wonder why it looks like shit and is inconsistent
hey anyone able to help me with this code? my coroutine isnt stopping, but the stop code is getting called private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player") && fog == true)
{
StopCoroutine(TearGas());
Debug.Log("stop Coroutine");
}
}
IEnumerator TearGas()
{
while (takeDamage == true) // Infinite loop
{
takeDamage = false; // Disable damage temporarily
Debug.Log("Player affected by tear gas, cannot take damage for a moment.");
yield return new WaitForSeconds(1); // Wait for 1 second
player.TakeDamage(damageAmount); // Apply damage to player
Debug.Log("Player took damage from tear gas.");
takeDamage = true; // Re-enable damage
// Yield control back to Unity until the next frame
yield return null;
}
}
how do i make it look like its a c# code? btw like the code above mine
read !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.
// private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player") && fog == true)
{
StopCoroutine(TearGas());
Debug.Log("stop Coroutine");
}
}
IEnumerator TearGas()
{
while (takeDamage == true) // Infinite loop
{
takeDamage = false; // Disable damage temporarily
Debug.Log("Player affected by tear gas, cannot take damage for a moment.");
yield return new WaitForSeconds(1); // Wait for 1 second
player.TakeDamage(damageAmount); // Apply damage to player
Debug.Log("Player took damage from tear gas.");
takeDamage = true; // Re-enable damage
// Yield control back to Unity until the next frame
yield return null;
}
}
there, now, hey anyone able to help me with this code? my coroutine isnt stopping, but the stop code is getting called
thanks
That is not how you stop a coroutine.
oh so im just stupid? i figured it was cause its the opposite from the starting
Coroutine cor = StartCoroutine(MyMethod());
...
StopCoroutine(cor);
huh?
You have to store it in an object to stop the specific one
StartCoroutine returns a Coroutine object
ahhhhh ok
StartCoroutine just tells unity about it so it can be handled properly. the coroutine's logic happens when you call the method
RoomInst = Instantiate(RoomPrefabs[RoomPicker], new Vector3(1, 1, 1));
how come the new vector3 is underlined red. Compiler Error CS1503
fixed it! thanks
if you supply a position you also have to supply a rotation
if you don't want it to be rotated, use Quaternion.identity
because that overload takes a Transform not a Vector3. Please read the documentation
no overload of Instantiate just takes the object and a position
also next time don't give people the Compiler error codes, those are pretty meaningless to humans, ideally you read the description of the error itself printed to you
Cannot convert a to b
(vector3 to transform)
Literally 10 seconds reading the docs would have answered this but, hey, I guess that's too much to ask
the IDE and the Unity Log window spells it out too
Does anyone have experience with the Modular FirstPersonController?
Love this. (also: https://nohello.net/en/)
i cant seem to reference the Modular FirstPersonController in a script. is there a specific import? im using this one https://assetstore.unity.com/packages/3d/characters/modular-first-person-controller-189884
well why not open the script you want to reference, it tells you which namespace is belongs to
yes im using the right one
if you still can't reference the namespace its likely using assembly definitions
or your editor isnt configured lol
what did you try, then?
ctrl click goes to the right file
i can insert it in the inspector, however when i select it, it gives me type mismatch
and in a script it just won't find it while testing
Are you trying to reference a scene object from a prefab?
I misunderstood your problem -- I thought you meant you were getting a compile error
yes also tried that
i thought vector2 is a transform
so i would i put it
so your IDE doesnt tell you things?
Instantiate(prefab, new Vector3(i * 2.0f, 0, 0), Quaternion.identity);
That is a valid use of Instantiate, yes
how is that different from mine
signature?
oh its because i didnt have the Quaternion.identity
consider reading the code you wrote
yes
you have to pay attention to the code you're writing
so you were wrong
what?
what?
look at the signatures
where do you see one with Object and Vector3
i give you 100$
because i had wrote the transform bit correct
it was the fact i didnt use Quaternion.identity
You never wrote anything involving a Transform
not at all
You showed us code that tries to pass an object and a Vector3
a Vector3 is not a Transform
it will never ever be a Transform
there is an overload for Instantiate that takes an Object and a Transform as the two arguments
But this is irrelevant, because you weren't passing an Object and a Transform
the amounts of parameter you use can change signature
didn't i tell you this
yes you did, and it fixed it. Thanks
thanks for the help anyway
do you understand this, at least..?
understanding WHY it fixed it is more important
rather than just blindly making changes until the compiler stops yelling at you, yes
Still don't understand why GetComponent<FirstPersonController> does not work, however i created a workaround by manually assigning in the inspector
that'll work if you have a FirstPersonController on the same game object
do you?
didn't know it had to be on the same object, is there a way to get one from the project in general?
explains a lot though 🤣
but then i have to place it in the inspector, right?
you should just assign it in the inspector, directly
[SerializeField] FirstPersonController firstPersonController;
no GetComponent call needed
anyone have any good tutorials on procedual generation for 2d platformer , with different room sizes?
Anyone know why hardcoding my listeners works, but using a for loop doesn't?
Basically, I'm instantiating 25 Prefab Buttons, and then setting listeners for each button all in code.
Everything works perfect except the following code
{
DayButtons[i].GetComponent<Button>().onClick.AddListener(() => LoadDay(i));
}```
But hard coding it does work
```DayButtons[0].GetComponent<Button>().onClick.AddListener(() => LoadDay(0));
DayButtons[1].GetComponent<Button>().onClick.AddListener(() => LoadDay(1));
// etc...```
Oooh it's this one
It's tricky
Basically, the anonymous function is capturing the i variable, so they all wind up using the same value
Thanks Fen! I think this should make it work 👍
Hi all. For some strange reason whenever viewing a TMP asset at a certain Y axis the submesh is omitted from view. I'm stumped on this one if anyone could tell me what I'm doing wrong.
This issue can be replicated both in the editor and during runtime.
It only happens when I use the <mark> tag to add the background color effect.
not really a coding question but maybe check if texture behind the text is not transparent otherwise you run into sorting by pivots
Changing transparency has no effect
oh it's some sort of submesh? Does changing the sorting layer not work with it?
It does, but then whenever I try and update my prefab or built it revers...
there's obviously some sort of sorting issue problem and usually you see this behavior when objects are both transparent and are on the same sorting layer.
rather, there's no depth sorting so it defaults to sorting by pivots
If I change the Order in Layer attribute to 1 from 0 in the TMP_Sub Mesh component class the issue is resolved. I just can't get it to "save" that change which makes me think there's another underlying issue
as a bandaid just set it at runtime in start maybe
That's not good enough tbh...
I really don't understand why the sub mesh's properties (all of them) revert on build/runtime
If I set the TMP transform.z to 0 and then the TMP_Sub Mesh transform.z to 0.013 the issue is resolved so it's obviously a z-clipping problem. I just don't understand why using the <mark> tag causes this issue and what an efficient alternative would be.
sometimes generating a for loop in VS gives this... what gives?
for (global::System.Int32 i = 0; i < length; i++)
{
}```
if (!(transform.Rotate(floatV,0,0) > transform.eulerAngles.x)){
whats wrong?
wait
nvm
what are you even doing lol
i m doing it wrng
not shite lol
what are you trying to accomplish
what's the part you're confused on? the type?
https://github.com/dotnet/roslyn/issues/71542
seems to just be an issue but does it work if you have the using System statement?
just confused on why Visual studio is doing this
seems to be the exact issue i just linked above
ahh this seems to be my issue
ok, but what part of that is "this", isn't that what snippets are supposed to do
I was doing it wrong
well I want the simplified version lol
it never did this before, I don't think..
im trying to limit the rotation
you want clamping
yes
oh jeez
just use cinemachine if you're making a camera script. these magic numbers will fail very quickly
because you are using magic numbers, and the code doesnt make sense itself. You are comparing the y angles and then trying to rotate the X axis by some -floatV value
because you cannot use eulerAngles like that
oh no
i keep losing my sense of logic
also when in doubt, debug your values
well i now have a good news and a bad news
the good news is that it stops me
but the bad news is that i cant move the camera anymore
i will use cinemachine anyway! thanks for ur help
what game mechanic are you going for here
it works now i changed the code that it looks at float y value
float currentX = transform.eulerAngles.x;
// Normalize angle to -180 to 180 to compare easier
if (currentX > 180) currentX -= 360;
//
// Calculate desired change code
float desiredChange = -floatV;
// Check if the camera is allowed to rotate up or down, basically
//desired change > 0 means that its going up // desired change < 0
// means that going down.
if ((desiredChange > 0 && currentX < 45) || (desiredChange < 0 && currentX > -45))
{
transform.Rotate(desiredChange, 0, 0);
}```
first person shooter game
The y Rotation is handled by player object, X rotation handled by camera
but as i said its pretty bad ig i will go for cinemachine or smthing
if it works it works
Hi, tell me does anyone have an example of PlayerAnimator with Idle, Walk, Run, Crouch, Jump management and rotation to the right, left and turn around please? and how could the PlayerMovement script be with this management of animations?? Thank you in advance, please mention me
what am i doing wrong? I can't seem to put the Player object in the Script slot.
does a Player component actually exist anywhere?
He just didn't set it
here
i cant set it
Does it have a Player component attached to it?
the name of the game object is completely irrelevant
But Fen, he doesn't even get the Player component in his script?
but I'm getting the feeling that the object named "Player" has no Player component attached to it
Well, you didn't set it before, and your not getting the PlayerComponent from anywhere. So it's always null, hence the null pointer reference exception.
Show the inspector of the Player object
the point appears to be to serialize a reference to a Player
so it be unreasonable to use GetComponent to assign that field
Sure, but he said this, that's what's confusing.
it worked before but after working on player input and stuff it broke and now i cant seem to figure it out.
Show the inspector for the Player object.
er, wrong reply
yes, because Debu is trying to serialize a reference to a Player
until you show us the inspector for the Player object, there is nothing else I can do to help
what about PlayerVisual?
inspector of the empty player object
There is no component named Player here.
If you want to refer to the PlayerInput component, then you need to refer to that, not Player
uhh okay.. what am i suppose to do now? 
i literally just told you how to fix it
do you not understand what this line of code is declaring?
[SerializeField] private Player player;
this is the game input script.
its been 2 hours with changing scripts. now my brain isnt catcing up with stuff
ughhh
This is a field that can hold a Player.
It cannot hold ANYTHING else.
If you want to drag an object into this field in the inspector, it must have a Player component on it.
If you want to refer to something else, then you must change the type of that field
so the empty game object wont go into that slot?
Correct, because that game object does not have a Player component attached to it.
thats is named player. i thought it works like that...
When you drag a game object into a field that holds a component type, Unity looks to see if the game object has a matching component on it
That is absolutely not how it works.
C# doesn't care about the exact names you've given to your game objects
The type system doesn't even know about those names
all it knows is that you said that field holds a Player
If I write "dog" on a piece of paper, that doesn't turn the piece of paper into a dog
i see, so what makes that empty object as the designated object (player for this case)?
You must attach a Player component to it if you want to be able to drag it into that field
The entire point of this is to let you store a reference to a Player
After all, as we can see in the same script...
you run player.IsWalking()
obviously you're calling the IsWalking method on a Player object
if player was actually a GameObject, then this would make no sense
i didnt think of it that way 
more generally, the entire point of C#'s type system is to let you know what things you can and can't do with your variables
you can do different things with a Player variable than you can with a GameObject variable
okay. so how do i add a player component onto the Gameobject in this case. my enpty player object.
surely you know how to add a component to a game object..?
yes
well then, do that
what is a player object? the script?
You wrote a script named Player.cs, yes?
that defines a class named Player
that extends MonoBehaviour, presumably
if you don't understand what any of this means you should stop what you're doing and use !learn to figure out how Unity works
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
this is some really fundamental stuff here
my bad i deleted some shit and i cant figure it out what. maybe that messed up.
i definitely had something attacted there xD
you do in that screenshot, yes
okay okay. it resolved hhh
i somehow deleted the component and i was verifying all the codes n shit for 3 hours T_T
im looking into it :)
thanks @heady iris
@heady iris NullReferenceException: Object reference not set to an instance of an object
Player.Update () (at Assets/Scripts/Player.cs:14)
T_T
Then you tried to use a null reference on line 14 of the Player.cs script
gosh ill create logic from scratch
sounds like gameInput was null, then
Hi there, I'm trying to spawn GameObjects where I had TreeInstances, but when I try to spawn the tree, it's not even getting spawned on the same terrain
So how are you spawning them?
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private float moveSpeed = 7f;
[SerializeField] private GameInput gameInput;
private bool isWalking;
private void Awake()
{
// Ensure gameInput is assigned
if (gameInput == null)
{
gameInput = FindObjectOfType<GameInput>();
}
}
private void Update()
{
if (gameInput == null)
{
Debug.LogError("GameInput is not assigned!");
return;
}
Vector2 inputVector = gameInput.GetMovementVectorNormalized();
Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
transform.position += moveDir * moveSpeed * Time.deltaTime;
isWalking = moveDir != Vector3.zero;
float rotateSpeed = 10f;
transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
}
public bool IsWalking()
{
return isWalking;
}
}```
@heady iris i updated the player script
for some reason netcode will just not work on andriod for me. it works fine when i test it on my pc but when i build a apk file to test it on my phone it just wont work. my phone dose not want to connect as a host or client. anyone got a idea why this might be happning?
now it works .. finally. took me 4hrs 
I wanted to set up some rotating platforms with in the middle but something happened and everything now has the same imovable pivot point
I cant see where I am moving my empties becouse of this
There is a button on the top bar
show the whole editor
what to do with it no mater what I choose its always the same
try the other one. it sounds like an issue caused by one or both of those
If its not then i have no idea
nothing changed
I managed to find a fix
its unity glitch
selecting this tool fixed the issue
Why is that a glitch 😄
You sure you werent in the wrong space (world,local)? What version was it, so maybe you can file a bug report if it was a bug
nope
to my knowladge its fixed in later versions
Ahhh okay 🙂 Good to know
!bug got a strange bug I'm trying to resolve:
using Unity 2022.3.13 and TMP 3.0.3
TMPInput component keeps breaking....
I create a TMPInput object in a prefab and everything looks fine - when instantiating the prefab, (using Addressables.InstantiateAsync) the input isn't working.
when opening the prefab again, I see "the associated script cannot be loaded" where the TMPInput was....
I have no copile errors in the project...
🪲 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
Are you sure you are not instantiating into your prefab instead of the runtime prefab instance?
not sure what you mean.,...🤔
are you creating the tmpinput scriptwise or just in the inspector?
I created in manually while working on the prefab
Ahh okay, gfot you wrong there. Thought the adding breaks the input. Did you check for updates on the package?
yes, no updates
and you are using this? https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.3/api/TMPro.TMP_InputField.html Did you try to add it to another object outside of the prefab?
Strange.... seem to be working in a diffrent prefab....
So.... readding it worked (tho i tried this before....) i think im doing something that breaks it.... hold on
Are you somehow in playmode or something weird?
No. but i think what fixed it was clearing the Library....
I cleared the Library based on a post i read online - but I did not try to recreate the input fields after that (did try it before). now that i recreated them, it seems to work fine
Anyway, seems to work fine now. thanks for the help!
Does anyone know, if iOS/visionOS fires the Application.lowMemory before the app crashes or when it already happened because no new memory could be allocated?
Docs say, you can use it to prevent the app of being terminated, but some experience knowledge from someone actually using it here might help
I love ScriptableObjects so much
Is there any way I can detect a user entering full screen with Alt+Enter?
not a straight forward way, you have to be creative
since alt-enter is a windows thing anyway
doesn't alt-enter just resize the window?
it switches it to full on fullscreen mode from window and vice versa
My problem is, that I have a resizable window, but when the user enters full screen it should go to native desktop resolution instead. I've build a way to change the resolution if the user clicks the Fullscreen Toggle button but it's not working with Alt+Enter unfortunately... Guess I'll need to manually check if it is in fullscreen and update the resolution?
yes you would have to maybe disable the alt+enter (same games do)
and you can make a toggle, only way to know for sure I think that you're switching each time
Does anyone know how to handle events when using the Unity Asesprite Impoter? the Docs only show how to add an event not how to call a function with it
it's just standard animation events
so if you add event:Foo to a cel, then any component on the same object as the Animator will get its Foo method called when that frame is hit
I just updated to unity version 2023.2.20f1 - can someone explain to me why this gameobject "Text - Header", which is part of a prefab and I disabled its gameobject, is showing up as the default grey text color? Is this a bug or something?
How does it make any sense for it to be that color?
Its one of their official releases still, how is that "outdated"? Lol
are you saying you have Unity 6 and it doesn't do this with the color?
idk ask the ones who made the website
I'm saying its likely a bug and you're using an outdated version
so you're just guessing? you don't have a newer version that doesn't do this?
if we want to take the word "official" like its worth a bone . Here
have you tried actually downloading 6 and testing the project to see if its a bug with 2023 or not ?
No, I dont want to use 6
suite yourself then idk that makes no sense. 2023 wont get updated
It's not a bug, it just means that the gameobject is not active in the prefab
there ya go
any idea why they choose to show that by having it be the exact same color as an enabled, non-prefab gameobject? I'm seriously trying to understand the reasoning here lol
You should likely not be using 2023 either than. Use the latest lts, which is 2022
ok so 2023.2 uses the new pricing plan? I thought the pricing plan only affected versions called "6" and beyond
Seriously, this is the kind of thing that excercises your brain?
No version now uses it.
And I doubt you're gonna make a million a year
or are you just saying that because 2023.2 wont get an LTS?
You should use LTS, yes
2023 lts is unity 6
No, 2023 will never be LTS, and guess what Unity 6 will not be either
uhhh yes? why would you choose to make things more confusing to recognize at a glance? It doesn't make any sense to me. Thats why i came here to see if its a bug, and if its not, trying to understand why it would be that way
its a bug because it should not be light gray but faded
like give me one good reason why it should be the exact same normal grey color, when they could pick any color? thats why i am confused, lol
what do you mean? What will the next LTS be?
Me chose? I've used Unity long enough to never question their decisions, almost all of them are nonsensical, I've just learned to live with them and GET ON WITH THE BLOODY JOB
like I said its 6
"why would you choose" is directed at Unity choosing to change the color - obviously you didn't choose since you cant make that decision rofl
And you fretting about something you cannot change is equally nonsensical
so you just accept anything that happens to you without questioning it? okay
"Happens to you" 
Things I have no infulence over, sure, anything else would be futile and a waste of energy
fixating on an icon color when there is nothing you can do to change is just wasted energy and time
rofl
coming in here wondering why something seemingly got changed for the worse for no reason - trying to see if its a bug maybe, or if there is a reason for it to have been changed - and you guys are suggesting to not care about it?
does anyone know why it got changed? is there something I'm missing?
ok somaybe it is a bug, or some other reason/condition for it to be 'grey' colored text
exactly, it is not 'something that got changed', so your initial premise is incorrect to start with
no shite, I said that a while ago..
2023 was literally beta
i dont even know what you're talking about, lol. I updated my project and it looks different now. It changed
you would think it had bugs..
Its literally listed in their official releases
This is, and has never been, a code question btw
its not in the hub, that gets updated more idk what to tell ya
their website is dogshit at times cant deny that
it is in my hub, but I admittedly have an older version of the hub
then see its failure on you
so its my fault they list it as official on an older version of the hub that they still update? 🤣
ok so blame everyone else but you. Idk mate, move on . Do something constructive lol
seeya
lol coming in here and asking questions is somehow "blaming"?
thank you for checking this
i appreciate that
wasn't trying to come in here and argue with people, no clue why you guys jumped to Unity's defense with my question
you went on a whole tangent/tantrum of unity design choices for the software when meanwhile it was just a bug..
my literal question when i came in here was "is this a bug?"
I did say it probably was so because its an old version and it didn't look normal
And you were told, no it is not, but yet you continue to winge
"is this a bug?"
"maybe"
thats an answer? 🤣
aight im done, i appreciate you checking @rigid island and sorry that for some reason everyone thinks im being a jerk or something
As I said. This is the wrong channel. Please stop
mate you are in development you outta learn how to test stuff yourself, i told you try unity 6 with that project and you refused what more you want
Everyone could just stop escalating it
what channel should I be using?
you are saying this, but then @rigid island posted a screenshot from Unity 6 showing a disabled gameobject and its blue
yea my bad I should have asked there
People are wrong sometimes 🤷♂️
indeed it should've been blue
Steve is just a community member
yes, Unity change their colour schemes from version to version
its also blue on 2022
Definitely looks like a bug to me. Not sure why anyone would say otherwise. Time to move on
thanks... yeesh
huh, I didn't notice that before
and i've been using 2023.2.20f1 for a while
that is definitely off!
Hey !
void Update()
{
if (EnemySelector.Instance.CurrentTarget != null)
{
EnemyHealth enemyHealth = EnemySelector.Instance.CurrentTarget.GetComponent<EnemyHealth>();
if (enemyHealth != null)
{
int ratiohealth = (enemyHealth.CurrentHealth / enemyHealth.maxHealth) * 100;
slider.value = ratiohealth; // Mettre à jour la barre de vie
// Arrondir le ratio de santé à 1 chiffre après la virgule pour une meilleure lisibilité
enemyHealthText.text = "Health: " + " (" + ratiohealth + "%)";
}
}
}
}
I dont understand why in my code, when the enemy take 10 damages and his currentheath decreases, "ratioheath" pass from 100 to 0 instantly, no 90. Someone know why ?
intigers
you are doing integer division
(Dividing two int produces an int)
so if you did 9/10
it will be 0.9 which gets truncated to 0, and 0 * 0 = 0
Oh okay thanks !
what stops someone from implementing an interface and then leaving one of the functions in it empty? If nothing is there to stop them, why add the forced function call in the first place?
Nothing stops them, and that isn't even abnormal
Why add it? Because an interface is a contract that it will exist, not that it will do anything
but wouldn't that just lower performance by calling extra unnecessary (if any) functions? Considering it can be ignored either way, I don't see a reason not to allow the programmer to call the functions they choose and just not call the others
granted the performance cost would be very tiny
empty functions is usually one of the arguments brought up for "composition vs inheritance". at the end of the day, it really doesnt matter and especially as an indie dev it is not worth caring about
So tiny it is basically free. But sure.
Just make the architecture better
i see then, thanks.
There is absolutely nothing in any programming language, past, present or future that expressly says that how it is used has to make sense
ah, so programming commonalities then
thanks
You are the one who has to supply the sense, all the language has to do is compile
Hi, I'm using this to delete the TreeInstances at runtime. But how do I delete them without permanently deleting?
List<TreeInstance> newTrees = new List<TreeInstance>(0);
terrainData.treeInstances = newTrees.ToArray();
I've created a script that implements IMoveHandler because I wanted custom events for when the user presses up or down, however, this seems to make it so it consumes the event and I can no longer move between any elements with this script and I just want it to interject before the event happens so I can still actually move between Selectables, is there a way to fix this?
nvm I got it
If you want to keep the old trees in memory, you could just store terrainData.treeInstances in a variable
What do you mean?
Like store it in a variable then delete them from that variable?
But after the game is stopped running, the variable will delete?
If nothing holds a reference to the variable, then yes
You want to restore old trees after you quit playing?
Is it just in editor or in built game too?
I'm creating them in the editor, looking to delete them at runtime. But if the game stops running, then runs again, I want all the trees from the mass-trees placement to spawn again
I found an alternate solution so I don't need a solution for this anymore
But just curious at this point if you have a way to not permanently delete treeinstance at runtime
It's not important for now
One thing to try is to Instantiate the terrainData (to make a clone of it) at runtime, then assign it to the terrain
And modify the instantiated terraindata, not the original
If I remember right, terrainDatas are stored as assets
So when you reload the scene, the terrain would just use the old terrainData
I haven't done this though. Just a theory
Hello, I'm having trouble with my raycast Field of View test
there is a buffer in between the mesh and the wall, could anyone help me w/ this?
thank you and i can show the script for it
the collider for the box is normal btw
I'm not a specialist in this, but I do notice that the raycast is actually going through the top-right corner. It seems to me the hitbox is off-center
when you zoom into the collider of the box it shows this:
You'd have to show the code of course
public class fieldofview : MonoBehaviour
{
[SerializeField] private LayerMask layerMask;
private Mesh mesh;
private float fov;
private Vector3 origin;
private float startingAngle;
// Start is called before the first frame update
private void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
fov = 90f;
}
private void Update()
{
Vector3 origin = Vector3.zero;
float fov = 90f;
int rayCount = 100;
float angle = 0f;
float angleIncrease = fov / rayCount;
float viewDistance = 50f;
Vector3[] vertices = new Vector3[rayCount + 1 + 1];
Vector2[] uv = new Vector2[vertices.Length];
int[] triangles = new int[rayCount * 3];
vertices[0] = origin;
int vertexIndex = 1;
int triangleIndex = 0;
for (int i = 0; i <= rayCount; i++)
{
Vector3 vertex;
RaycastHit2D raycastHit2D = Physics2D.Raycast(origin, UtilsClass.GetVectorFromAngle(angle), viewDistance, layerMask);
if (raycastHit2D.collider == null)
{
// No Hit
vertex = origin + UtilsClass.GetVectorFromAngle(angle) * viewDistance;
}
else
{
//Hit
vertex = raycastHit2D.point;
}
vertices[vertexIndex] = vertex;
if (i > 0)
{
triangles[triangleIndex + 0] = 0;
triangles[triangleIndex + 1] = vertexIndex - 1;
triangles[triangleIndex + 2] = vertexIndex;
triangleIndex += 3;
}
vertexIndex++;
angle -= angleIncrease;
}
mesh.vertices = vertices;
mesh.uv = uv;
mesh.triangles = triangles;
}
}
Your code is treating world space positions and mesh vertex positions as of they're in the same coordinate space
Is the MeshRenderer always at position 0,0,0 with rotation 0,0,0 and scale 1,1,1?
wait the renderer isnt at the origin
i'll try to set it rn
ayyy it works now
thanks 👍
Hi guys, i have an issue, i'm using UVCS and the main branch have been forgotten, i'd like to push a branch into the main to get a latest version, but when i merge, I have some changes that are kept from the main and does not take all the code from the branch i merge from
I short i want to override all code from main by the code from a new branch
guys what ı can do for auto code complete in "Rider" IDE
sometımes it not completes and ı dont know why
got any prefer?
when ı say "kartOzellıkNesnesı.can" or somethıng
Rider seems to think you have decompiled that code
ıt cant fınd ıt
what thıs mean
It means something's gone very wrong. It shouldn't say "IL code" anywhere unless you're inspecting someone else's code
Make sure the JetBrains Rider Editor package in Unity's package manager is up to date, and restart Rider
it is like that
That's the newest version anyway
anyone got any ideas on why my unity packages are gone? I can't reference Unity.TextMeshPro assembly because unity doesn't import UI package for some reason (files are there when I show in explorer, reimport does nothing)
This is on new project on Unity 6000.0.5f1 updated yesterday from 6000.0.1f1, it has been like this on both versions
Sadly this is just an annoying bug. You have to Reimport All to fix it
I have a very strange bug with input actions. I have arrow keys for aim and space for shoot, but whenever i try aim diagonally, so like up+left arrow keys, the shoot input DOESN'T trigger anymore. But, shoot DOES trigger when aiming up+right. Any ideas on what could be causing this?
shader trancparency not working
fixed4 frag (v2f i) : SV_Target
{
fixed2 uv = i.uv;
fixed2 center = fixed2(0.5f, 0.5f);
fixed sqrDistance = pow(center.x - uv.x,2)+pow(center.y-uv.y,2);
float angle = atan2(uv.x - 0.5f, uv.y-0.5f);
if (sqrDistance < pow(.5f, 2) && degrees(angle)+180 < _Angle){
return _Color;
}
return fixed4(0.0f, 0.0f, 0.0f, 0.0f);
}
Tags { "RenderType"="Transparent" }
ok i fixed it
#archived-shaders is the right channel for this next time
Whenever I write code I endup having so many huge if statements
I dont know if this is a the right place for this question but im trying to have my enemy prefabs get the player position but i want to use something more efficient then findObjectWithTag
dependency injection #💻┃unity-talk message
Probably a hardware issue, some (mostly cheap) keyboards have that issue when trying to press 3+ buttons at once
Yeah just tested my cheap keyboard here https://keyboardchecker.com/
And I can see the exact same issue - "Right + up + space" works but "Left + up + space" doesn't
yeah, it depends on how they detect the key presses
some check if a key is pressed on each row and column
So would you guys say directly modify velocity for movement and otherwise use add force?
Thats a personal preference and there is a no right answer unless you are doing something fundamentally wrong. I generally move 2d characters by velocity and use add force for jumping, but on another project do it completely different.
Has anyone ever experienced a prefab with a custom editor script not storing its values when exiting prefab mode?
are you marking it dirty
The prefab or the editor related class?
the prefab when you modify it with the editor script
Dang, no I do not. Would this here already be what I gotta call after applying modified properties?
#if UNITY_EDITOR
var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null)
{
EditorSceneManager.MarkSceneDirty(prefabStage.scene);
}
#endif
how do I pack multiple layers into 1 layermask? if I expose a layermask to the inspector and just select the layers I'd like to include there and then print the integer of that layermask its always 0 which obv. means that not a single mask is active.
it sounds like you are possibly resetting the value stored in the layermask if it is just printing 0
if so then I have no idea how as its just public LayerMask layerMask; into print((int)layerMask); (print on Start)
Dumb me was changing the values of the targetObject directly instead of the property... my bad and thanks for the hints 🙂
nvm, fixed it. I had a list of layermasks before I realized I could just check multiple layers inside the inspector and I was setting the list but printing the singular layermask
Thank you 🙂
Whats the keyword I am looking for when I want to "clamp" a vector2 within a rect? My use case is a pointer that visualizes the direction of an out of screen POI. If I'd draw a line A from the screen center to the out of screen POI I want to pointer to be where the screen rect intersects with A.
then it usually means you need to learn some design patterns to make better code
If that is something you are trying to reduce, could you provide an example where you might have a lot of if-statements?
So im making procedural level generation for a hallway and I have 6 set presets that are different sizes therefore have different vector displacements for them to be attached for each one. They are randomly picked and attached together in a line. Then after 10 unique sectors the game moves onto a new area where 6 others presets are picked and a default level transition prefab is placed where the cycle repeats
I have 7 large if statements with 5 if within each
2 options come to mind that may be situation based, If those statements are iterating over the same type, you can try a switch-case instead (though that wont reduce your code just organize it differently), otherwise if your statements have repeat or similar code, you could create a bool-returning function and pass what you would normally have in the if-statement, as params instead (possibly as a for-loop), though it may depend on why you need those if-statements to begin with/what they are actually doing, are they just checking/comparing vector values?
Hi everyone, I was wondering if someone could help me with particle triggers / collisions. I've been looking and I cant find anything that helps me with what I want.
I have like a toxic trap when spawned a particle starts spreading but it does not detect the enemy, I have colliders in the enemy, I have the script attached to the particle with OnTriggerEnter and OnTriggerExit, but I dont know how particle works. Maybe it could be an stupid error, something that I did not see or something else.
Also I'm new to unity and just started studying it on school and I'm making a project for school 🙃 so dont be hard on me
Maybe Rect.PointToNormalized is what you want?
judging from the output, probably not
afaik, it just has to be a clamp for each dimension
though, you could make extension methods for it
i did, i just don't remember where...
There adding position displacement to instantiated prefabs. but at this point it works + I have optimized it to the point where I've halved the if statements . So ig I'm fine now
is there a way to make the two bone ik from animation rigging work with targets that are being transformed by their parent? the contraint does not care about any movement that isnt done directly by the target object itself and thats really annoying.
Weird bug for me.. I have a dialog box I wanna show once to a user, but something in player prefs seems to not be working as intended. Code:
public const string PlayerPrefsShownAsteroidInfoString = "ShownAsteroidInfo";
private void OnEnable()
{
bool hasKey = PlayerPrefs.HasKey(PlayerPrefsShownAsteroidInfoString);
if (!hasKey || PlayerPrefs.GetInt(PlayerPrefsShownAsteroidInfoString) < 1)
{
v($"Player prefs key not detected. Showing info dialog. HasKey:{hasKey}");
OnInfoShownAutomatically();
}
}
public void OnInfoShownAutomatically()
{
InfoDialog.SetActive(true);
PlayerPrefs.SetInt(PlayerPrefsShownAsteroidInfoString, 1);
v("Asteroid info showing automatically. Setting player prefs key.");
}
"HasKey" is false on subsequent runs. I've verified OnApplicationQuit is called (and my understanding is playerprefs are written at that point). What am I missing?
and that "Setting player prefs key" line shows up in the log?
Also attempt to use the overload of GetInt() that allows you to specify a default value (pass a value < 1 since you check for that), to rule out whether it's HasKey that has an issue. Doubt it, but worth a try
Any possibility you're calling https://docs.unity3d.com/ScriptReference/PlayerPrefs.DeleteKey.html at some point?
boing
Do you really have a method v to print something into the console?
Yep.
it's an arrow to the next line, clearly. c# 2d language confirmed
Does is just call MonoBehaviour.print?
and i(), w(), e(), d()
omg
Nah, it does some stuff with my logger DI
colors it, writes to files, expands stack traces when needed, etc
Is there any way that you call your scripts GM = GameManager, PC = PlayerController etc.?
info, warn, error, debug?
what's the v?
verbose
trace: am i a joke to you
This is actually looking so fine 🌴
comes from Android world.. Log.e(), Log.d(), Log.v() etc
im so glad i left
yeah, makes sense
as long as you understand it, all it matters more power to you
Log.info() is surely a lot less typing than Log.i()
bit more functionality than Debug.LogError()
I don't type log.info - that's the android method.. i just type i()
1 keystroke apart though 
I simply instantiate letter prefabs to spell out my message in the scene
O H N O !
with rigidbody physics, obviously
alphabetical log levels when
wordart console message support
I have a script that's updating a bunch of material's properties. I want to make sure they update otuside of playmode so I can visualize changes to the properties in the editor viewport.
Issue is, if I just set the values of the properties inside OnValidate (which runs when a variable gets changed), they just get reset whenever the scene gets saved (serialization problem?). I was able to solve this by just updating the properties every frame inside Update and adding the [ExecuteAlways] attribute to the script but this causes quite a performance impact because I'm constantly updating a bunch shader properties even when they haven't changed.
How can I make sure the settings won't get erased when saving so I don't have to update them every frame?
This is how I set the properties
private void SetMaterialValues()
{
foreach (Material mat in Materials)
{
mat.SetFloat("_Cloud_Density", cloudScale);
mat.SetVector("_Cloud_Movement", cloudMovement);
mat.SetFloat("_Cloud_Strength", cloudStrength);
mat.SetFloat("_Cloud_Cover", cloudCoverage);
mat.SetFloat("_Cloud_Change", cloudChange);
mat.SetVector("_Cloud_Step", cloudStep);
mat.SetFloat("_Shades", shades);
mat.SetFloat("_Brightness", brightness);
mat.SetFloat("_MinimumDarkness", miminumDarkness);
}
}
Which is called by:
public void ApplyChanges()
{
if (overrideMatValues && Materials.Length > 0)
SetMaterialValues();
}
Which is called in the update function.
Variables getting reset means you might have to call EditorUtility.SetDirty
where did you get the references in Materials?
They're just added from the inspector.
if they're direct references to Material assets in your project folder then yeah @lean sail is right
Tried changing the code to this, but properties still reset when saving the scene.
foreach (Material mat in Materials)
{
mat.SetFloat("_Cloud_Density", cloudScale);
mat.SetVector("_Cloud_Movement", cloudMovement);
mat.SetFloat("_Cloud_Strength", cloudStrength);
mat.SetFloat("_Cloud_Cover", cloudCoverage);
mat.SetFloat("_Cloud_Change", cloudChange);
mat.SetVector("_Cloud_Step", cloudStep);
mat.SetFloat("_Shades", shades);
mat.SetFloat("_Brightness", brightness);
mat.SetFloat("_MinimumDarkness", miminumDarkness);
#if UNITY_EDITOR
EditorUtility.SetDirty(mat);
#endif
}
well silly question - where are cloudScale etc coming from
variables
also I should state this is just a monobehaviour with an [ExecuteAlways] attribute
ok so
could it be that these variables are the ones resetting when you save the scene?
Or I guess... you're not even going into playmode?
I'm trying to get them to update in editor without having to go into play mode
I can see that values of these variables aren't changing in the inspector when the scene gets saved so I don't think they're not serializing properly
Basically I'm not sure why it's not just working as-is.
What if you try https://docs.unity3d.com/ScriptReference/AssetDatabase.SaveAssetIfDirty.html
This is what happening btw. When it turns fully dark green, that's when I'm saving the scene.
Using that seems to never cause the properties to update
I can see the properties in the material ARE updating and staying updated too.
Figured it out, the script was relying on another script to blit a texture for the clouds which wasn't being called because the other script didn't have [ExecuteAlways]
I think it is just a wrapper for it. So they can write a single letter instead of potentially like 4 or 5 with autocomplete
no you can only use print() if its inside a mb (or class that derives from one ofc)
I think it just has to be called from one
Whereas, of course, Debug.Log can be called from just about anywhere
It's shorter
thats about it
Debug.Log also gives you option to pass in Object so you can click log and see which specific object has printed it
print can't do that
indeed
see "context"
Example: cs Debug.Log($"Click here to have {name} highlighted", this);
no you misunderstanding what it does
The object is highlighted in the Unity Editor
because if you have multiple enemies with same script, you want to know specifically which one printed it that value
yeah for debugging is very handy
the docs I linked you explains a bit
trial and error is perfectly fine
with time you want to speed it up, and thats why you begin placing more safeguards and debugs
unless its like deliberate though, i hardly use Null checking anymore (for "fixing" null refs)
you just find ways to ensure certain objects aren't null for example
dependency injection for example, you know for sure all objects are filled
usually you print if something isnt giving what you expect
my object isn't moving, debug.log the speed of the rigidbody is moving... what is wrong??
has to be something locking the player.. look at the inspector, oh Static is on.. ops
you can use Debug mode in the inspector to view private variables without serializing them, just not local ones.
acceptable at first, bad habit though imo
Yeah. Reference them in the inspector, depend less on Get Component and have prefabs of object-component combinations cached to avoid needing to create new objects with Add Component unless absolutely necessary. Good ways to avoid NRE.
like Visual Scripting?
Are you referring to visual scripting?
sounds like visual scripting
I can't even think of last time I used a GetComponent xD
he’s talking about visual scripting
null reference exceptions
null reference exception
Well, try get component for filtering on collision might be fine if we're intentionally not wanting to do anything to objects without our desired component 😅
you tried to do something with a variable, but it was null
it’s where you code by sticking together nodes and shit
Node based programming
oh yeah TryGetComponent for sure for the initial search in say a collision, true. Thats for runtime grab
for like IInteractable for example
whats GMS?
visual scripting makes your code look like this
oh nice, i used Game Maker as one of my first engines
but it was back when it was Game Maker 5-8
You would still be required to know logical operations but may ignore c# syntax and direct interaction with the Unity API - you kind of still are doing both though, relative to constraints.
Its shit in comparison, coding will always have more control of what you can do.
I recommend trying to just code. But yes, it is an option
well, yes. but also your code will literally look like that
For any project
believe me the code will be much easier to pickup
You need to know code basically in order to use any node based programming anyways
I came from doing drag and drop of Game Maker and ironically always thought GML and code in general was too complicated
there is a reason every game dev codes, instead of being that crazy guy that tries to connect shit on a bulletin board
oh you mean like 70% of Unreal devs
its so embedded even official Unreal howto- videos use it instead of showing you the C++ equivalent
visual coding gets really messy very rapidly, in almost every IDE I have ever seen
i remember in game builder garage, where there is a hard 512 node limit, programs were pure spaghetti
no joke blueprint knowledge is required on a lot of the job posting
It presents itself very nicely for minuscule tasks. It isn't very friendly for complex operations.
whoever made it though just has poor organization skills of graphs though
yea
thats a nightmare
unreal
this one has organization:
but to be fair a lot of people do write code like this, is just isn't as noticeable without the visuals lol
this is why we tell you to code instead of visual scripting
Problem is, most nodes might simply be a type declaration that unfortunately adds so much static (television interference) to the whole picture.
i have many script folders for a project, organized by topic
I bet if we used a plugin to show assemblies to Visual Script a lot of peoples code looks like this
i have a physics folder, with physics engine subfolder and collider subfolders…
you’re going to have a LOT of everything
more folders usually gives better organization
as moving things from their folders can break stuff sometimes
unity can be smart about moving monobehaviour files
Whereas with code and good conventions, you'd be able to view the types up top (or wherever they're grouped at) and focus on specific methods - having a method call or referencing some data won't obliterate your screen.
but sometimes it breaks some addons that depended on where the file was
not really
unity serializes all the asset files with a unique ID
You dont use the path in code
You use their TYPE
class is a type
if you want a script aka normally a class, you just say the name
public class Foo
{
}
public class Bar
{
public Foo foo;
}```
yeah but you make the reference with the type you want but you grab the instance of it
so head would be a public property/field of Player class
why do you need code for that?
Hey, so I'm getting loads of errors when I run my game through a build that are not tied to a specific part of code? Unity outputs them with a really weird format, I am building with Mono and disabled stripping level
at EditorControls.Update () [0x0013f] in <659d7b57dffc4b95b6241f694d9a6632>:0
I'd like to know how I can find what the error actually is, since I can't get any info on it
why would u need code at all?
i dont understand how you would need scripting for this
I get that but all you need is the sprites inside a field
yeah but you would just keep the stored inside an array or something
you dont have to grab "assets" via code
you can of course use methods like Resource.Load but its unnecessary
yeah but you can just drag and drop them into the inspector of that script
pain
also its very fragile, what happens if somehow you change name or change folders
thats why you normally make a field that is serialized in the inspector so you can drop any resource directly there and if its renamed its still there, or moved
assuming you moved them within unity ofc. Unity stores them by ID not by names
You can use anything, the question becomes.Why
if its 2D its frame by frame, if you have a skeleton yo ucan use IK
actually I think unity has 2DIK too so you can technically move it also by code
you mean a delay between switching clips? thats something you can do in the animator already though no ?
its great, it organizes all your animations into a single state machine
idk anything about your game to make a suggestion
so topdown view?
so what do you mean by frame by frame then
the animator could let you bind specific animations to certain direction of char
I'm sure Unity compensates for that with animation, though dont take my word as this is not relly code related
I have no idea about 2D /animation aside from basics 😅
yeah if they are same animations, topdown is easier to get away with that
it probably does same thing you're doing now
takes in a direction input can output different animation
so you're saying you're manually switching feet animations instead of animation clips?
yes thats what 2D blen does on the Animator
oh they called it something else myb
https://docs.unity3d.com/Manual/BlendTree-2DBlending.html
you should learn what an array is, you shouldnt require a line of code per object. in response to the part for 3d coding, the only coding for animations is really just setting the state or animation rigging. Unity already handles animations, its literally just plug and play.
if you're implying 2 lines per object, you're doing something wrong
It will be the same amount of code no matter how many objects you do that to
By simply looping the array
I have a question. Does anyone know if it is possible to load a scene before switching to it? I need to run a script in a scene to prepare a level.
Hi, quick question, why on the navmesh the auto generated links are not bi directional, they only go down not up
You can load it with async but perhaps should explain your situation as there might be other alternatives.
Maybe use the LoadSceneAsync function and then set the scene to enabled
I guess. Is it possible to save a level's state and go back to it? because i just reload the scene currently but i might not want to repeat the loading process.
its to load a tilemap from a file btw.
So any one know why?
This is the general coding channel, whereas I'm assuming your question is in regards to #🤖┃ai-navigation or non coding Editor stuff #💻┃unity-talk
Those would probably be better places to ask non coding questions. Otherwise if it's coding related, you might want to provide some code with your question.
If you're unloading the scene, then you'd need to save whatever information you want as loading it again will just load from the saved file. You could save this information to some object in DDOL so you arent loading from file again or find a way so you arent unloading and loading the scene again
Oh did not scroll down far enough, sorry about that, the "code" part will come next
I need a good terrain system for 2D games, basically i need that a player can collides with any type of terrain, slopes, etc. and the player must know which side is blocked by the terrain, someone knows about a good one?
The best one is the one you implement yourself.
also not a coding question :)
i tried to code 3 by myself, but they always have weird bugs that are hard to solve
where can i ask about that?
Alright fellas! I figured this might be the best place to help me with this issue as I've been facing it for a lil bit, as you can see with the first 2 shots there's a pretty significant spread but tight enough but the moment I try to shoot a close target the spread somehow hits the roof making it feel like an uncontrolled spread. This isn't a matter of the spread itself though else the spread would be huge during the first two fires. My bullets have a rigidbody with continuous collision detection and interpolation
It may have something to do with the speed but it just seems like the bullets are bouncing off the colliders and not registering the collision event which doesn't make sense to me
GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
currentBullet.transform.forward = directionWithSpread.normalized;
currentBullet.GetComponent<Bullet>().Damage = Damage;
currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
The code literally just spawns it in and hits it with a force
The attack point is the barrel of the gun and I prevent the player from shooting if they are too close so the gun can't be fired when it's just inside the target
Maybe #🖼️┃2d-tools
uhm but that is for artists
It seems mostly applicable, in my gut. Failing all else, there's always #💻┃unity-talk
Well, how about you look for help regarding these bugs instead of giving up?
Assuming they want to develop their own system, this channel is good enough for such a question
It almost looks to me like you're achieving the same area of spread at distance as well as at close range. To discount that theory, how are you calculating directionWithSpread?
I had the same theory at one point but I don't think it'd explain the roof hits, especially if I keep my spread under 1 but here's the entire calculation
Vector3 directionWithoutSpread = targetPoint - attackPoint.position;
float x = UnityEngine.Random.Range(-spread, spread);
float y = UnityEngine.Random.Range(-spread, spread);
Vector3 directionWithSpread;
Vector3 right = fpsCam.transform.right;
Vector3 up = fpsCam.transform.up;
Vector3 spreadDirection = (right * x + up * y);
directionWithSpread = directionWithoutSpread + spreadDirection;
targetPoint is just the result of a raycast hit
for testing, try using set velocity on the spread over the force
also try drawing gizmos where the bullets spawn
targetPoint - attackPoint.position;```
What is `targetPoint`?
Yes, your spread is the same distance regardless of how far the hit point is, so of course that would look extreme at close distances. You should rotate the direction vector by a spread angle instead
So I think that might at least be a factor, since the spread vector is being added to the vector between the gun and the target... At distance a spread of 1 unit would result in maybe just a handful of degrees of difference, but up close a spread of 1 unit could be pretty massive in terms of degrees from the target
Also your code here is going to vary extremely based on distance to the target
since you're not normalizing directionWithoutSpread
honestly it's jsut not a good idea to be using position displacement to do spread
you should use rotation angles
oh yeah always normalize direction* calcs
But at the very least, you need to normalize that direction vector
Huh, okay
a looooong vector with your offset will not be perturbed that much in angle
a short vector will be perturbed a LOT
hence what you see
Alright thanks!
yeah may want to funnel the bullets and use rotational spread cause you'll run into issues where it'll hit the walls on the side of you probably
Really I would do this:
Vector3 directionWithoutSpread = (targetPoint - attackPoint.position).normalized;
float x = UnityEngine.Random.Range(-spread, spread);
float y = UnityEngine.Random.Range(-spread, spread);
Quaternion randomRotation = Quaternion.Euler(x, y, 0);
Vector3 directionWithSpread = directionWithoutSpread = randomRotation * directionWithoutSpread;```
then again up to preference. I've seen guns in games that do kinda do positional spread (flak cannon in unreal)
or maybe just:
Vector3 directionWithoutSpread = attackPoint.forward;```
Just because I haven't gotten to use paint in a minute, here's an illustration of the original code (assume spreadDirection to be constant for the two scenarios):
I do run into an issue where if I'm facing a certain direction there's like no spread on the y but I can for sure figure that out on my own 😂
This actually helps a ton
Thanks for all the help gang! Immediately the spread is better
i was trying to make some kind of 2.5D view but, why do my sprite randomly disappear when the camera is further away from ground?
the clipping planes on your camera (near and far)?