#💻┃code-beginner
1 messages · Page 712 of 1
not sure I'm following this part
i think i need sleep, its almost 2 am xD
will come back tommorow to this mess
basically
if its 0, it doesnt serialize
even if its in list
so i get lists like this
because alpha is 1 by default
but a float by default is 0
i dont know how to override the alpha to 1 inside the list itself
I'm imagining basically (psuedocode):
serialize() {
for (i from 0 to defaultarray.length) {
if (myData[i] != defaultArray[i]) {
writeOverrride(i, myData[i]);
}
}
}
deserialize() {
deserializedArray = defaultArray;
for (override in overrides) {
deserializedArray[override.index] = override.value;
}
}```
and we could have some lists that are like this
yeah my brain isnt braining right now
im looking at this wall of text and i dont understand how i could make this
i understand how it would work
but dont know how to make the serialize part in the newsoft json
im not trying to make my own serializer right now 
Like I said you make a custom JsonConverter for your type:
http://newtonsoft.com/json/help/html/CustomJsonConverterGeneric.htm
ah, i understand now
readjson == deserialize
writejson == serialize
I do wish their example was a little more in depth
yeah its just one example lol, but still i understand, will implement tommorow, thanks
Do ya'll know why my dash code isnt working, Ive looked through it and for the life of me I can'tfigure out whats wrong
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public Rigidbody2D rb;
private Vector2 moveDir;
private float activeSpeed;
public float dashSpeed;
public float dashLength = 0.5f, dashCooldown = 1f;
private float dashCounter;
private float dashCoolCounter;
// Update is called once per frame
private void Start()
{
activeSpeed = moveSpeed;
}
void Update()
{
ProcessInputs();
}
private void FixedUpdate()
{
Move();
}
void ProcessInputs()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDir = new Vector2(moveX, moveY).normalized;
if (Input.GetButtonDown("Dash"))
{
print("success");
if (dashCoolCounter <= 0 && dashCounter <= 0)
{
activeSpeed = dashSpeed;
dashCounter = dashLength;
}
}
if (dashCounter > 0)
{
dashCounter -= Time.deltaTime;
if (dashCoolCounter <= 0)
{
activeSpeed = moveSpeed;
dashCoolCounter = dashCooldown;
}
}
if (dashCoolCounter > 0)
{
dashCoolCounter -= Time.deltaTime;
}
}
void Move()
{
rb.velocity = new Vector2(moveDir.x * activeSpeed, moveDir.y * activeSpeed);
}
}
put logs
that print("success"); is kinda useless
you need more and preferably print actual values
Yeah I was just checking that my Input manager was working cause I didnt know
I was using the wrong variable 😐
Hey, I got a question about scriptable objects
Context
I'm making a magic system in my game that you can only have one active spell in your spellbook and need to change it frequently. I though about making it with scriptable objects, but I also want them to level up in certain points of the game (altering the scriptable object).Question
How can I write values into my scriptable objects?
In this case, I want to be able to change my Spell Level from 1 -> 2 and vice-versa (Ex: When getting an upgrade / Loading a save file)
How can I write values into my scriptable objects?
the same as you would any other script
also whoops misclicked
I thought scriptable objects worked like separate instances from the actual script, how exactly can I reference it?
There's two routes you can go, with the first being more ideal so i'll elaborate on that more than the other
-
You basically make a "live" version of your spell class and have a sibling-esque relationship with your scriptableobjects. Here you would use your scriptableobject to give the "live" version of the class it's default values, then modify that instance of the class how you need
-
Runtime creation of scriptableobjects
I'll look into it, thank you very much 🫂
no each instance is made in your project folder you can reference them after by make the reference in code serialized
[SerializeField] ScriptableObject ScriptableObject;
oooo, ok I got it, thank you
Though as you might be already cautious about direct changes to scriptableobject assets at runtime will not reset when you exit play mode
yeah quite annoying especially since they do reset if changed outside of a unity runtime (meaning if the game was build they don't save after each load)
they could just reset them in unity after though
at least have it consistent you know
that would be inconsistent with how assets are treated in unity tho
i mean i guess :/
Hi there,
how can I ensure that monobehavior GUIs can register for events from controllers that are plain C# classes without being null? Calling a new Controller in awake and then registering for the event in onenable/ondisable always returns a null pointer because the instance is created too late.
How do you solve such a general problem?
Awake is called before OnEnable, so it shouldn't be null pointer.
https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
I suggest debugging it thoroughly or providing more details(code, errors, setup screenshots, etc...)
About DontDestroyObject scripts, do I have to assign scene-specific references during runtime?
Not quite clear what you mean.
do you mean DontDestroyOnLoad
DontDestroyOnLoad objects persists between scenes, and there are objects that only exist in certain scenes.
I know can manually find each of them in the script, but it feels tedious and possibly slow the game if it's large enough
So I'm looking for alternative if there is one.
- Finding is not always bad. If it gets bad, then perhaps there's a more basic issue:persisting too many separate objects between scenes.
- There are many other ways to get a reference to something, other than using the find methods.
does anyone ever solved gradlew.bat error when resolving android dependencies?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
A tool for sharing your source code with the world!
how can i add normal mapping for my textures?
seems easy to but i dont know
i just found out i can't inherit from plain class, so currently my banana can technically contains items like my pouch because i just jammed it all in Item class. no problem so far, but what is the correct way, make multiple classes ?
Why can't you inherit from a plain class..? 🤔
there is an error and from google ai it said
In Unity, you can inherit from a custom Item class, but issues can arise with serialization and editor functionality if Item is a plain C# class and not derived from MonoBehaviour or ScriptableObject.
It doesn't seem like you're doing any light calculations at all. There's no point in a normal map, as it's usually used as part of the light calculation.
do i not use the unity lighting?
You can, but I don't see anything related to it in your shader.
how do i use it then
or would it be better to make my own lighting system
i made an engine a while ago and the lighting was definitely very poor
im not that good with shaders
Well, this doesn't really say anything specific. Plain classes can be serialized if they are part of a MonoBehaviour/So or if you have a custom editor for them.
Definitely better to use what Unity provides. You'll need to research how to use unity shader includes and call the lighting calculation function from your shader.
(This is why you don’t use ai)
Honestly, I'd use shader graph instead of writing a custom shader.
but ive got structs and looping going on
Because it's gonna be a pain in the ass, especially if you don't have experience.
You can with a custom function/hlsl node.
But currently I don't see anything that is not implementable in a shader graph by default.
arent plain class not inheriting from anything by definition ?, it did said
"Use [SerializeReference] for polymorphic serialization of plain C# classes. This attribute allows Unity to correctly serialize and deserialize derived types within a collection or field, preserving their specific data. You might also need a custom editor to manage adding different derived types in the Inspector."
but im afraid ill break my stuff with current setup. maybe ill delve into it when im free
as a statement the text that ai provided in this specific scenario is not wrong
but as an answer to your question its pretty abyssal
base class usage in unity is extremely common and unity supports it explicitly
like anything in unity, things can go wrong if you do it wrong
Or you can take the unity standard shaders source code and modify them instead. Still gonna be easier than writing from scratch. Or at least use them as a reference.
and because its not a monobehaviour or scriptableobject, they way you treat them is abit different
It's hard to say anything specific without knowing your project/setup, but generally inheriting from a plain class is very much an option and is often used in unity.
yea i just test with empty new plain classes inheriting works fine. ill look into my prob
so.. my derived class needs constructor that supports my base class, it has to be written in certain way..
i didnt know the syntax alright
but i already made my container banana, ill refactor and change it later..
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
does anyone knew how to disco dance a text with code in unity
I want to create Flappy Bird in Unity but I can not handle Jump with new input system. Can someone help?
hello guys
i had a question i found this online tutorial for C# since i want to learn it instead of relying on ai 24/7 and wanted to know if what this tutorial teaches me will only be applicatble to websites and etc or help me in unity too is there a difference between unity C# and normal C#
there's some differences in how you specifically use it but overall you learn the same stuff
https://www.youtube.com/watch?v=r3CExhZgZV8&list=PLZPZq0r_RZOPNy28FDBys3GVP2LiaIyP_
i am following this tutorial seems pretty old(4 years ago) but looks promising
C# tutorial for beginners
#C# #tutorial #beginners
⭐️Time Stamps⭐️
00:00:00 intro
00:00:48 download Microsoft Visual Community
00:01:41 new project
00:01:59 change IDE font size
00:02:24 compile and run program
00:02:38 Main method
00:03:35 Console.WriteLine();
00:04:27 change Console font
00:05:18 Console.Beep();
00:05:40 conclusion...
the bestTime doesnt seem to be saved across sessions in the editor
will it work if i build the game?
or is something wrong with the script
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
If it doesn't work in the editor then it won't work in the build either
the code never saves anything to playerprefs
bestTimeL1 = PlayerPrefs.GetFloat("BestTimeL1", bestTimeL1);
PlayerPrefs.Save();
does this not work
No. You're not telling it what to save and where
SetFloat is for saving floats to playerprefs
bestTimeL1 = quickReload.timerTime;
if (quickReload.timerTime <= bestTimeL1 || bestTimeL1 == 0)
this is also wrong, if you've just set the both variables to equal each other then the condition on the next line where it checks if they're equal will always be true
No GetFloat finds any past saved data for the key string you'd need to use SetFloat to save to that key string.
yep that works thank you very much
ask in #🖱️┃input-system and provide some more info. what exactly is going wrong? are you getting errors?
Can anyone help me with understanding what the use of ADDING Time.deltaTime is, please?
I understand why we would multiply by it, but why would one add it to make a timer for example? How would that make any sense?
So i've added a RayCast to try and get the angle of a surface so I can modify movement on slopes, but the problem is that i'm getting the angle of the raycast relative to the surface normal instead of the actual incline of the terrain, and I don't know what I should write to get that angle.
https://paste.ofcode.org/daj5pGjCJ427y7r5Djvc9g
As a visual example to make myself clearer, the blue angle is what I get with my current code, the red line is the RayCast and the green line is the ground normal. I want to be able to get the value of the pink angle instead, but I don't know where to start.
The blue and pink angles are the same
im doing stuff like this to save BestTimes for different lvls is there a simpler way to do this?
How would I go about moving on low poly terrain, still following the mesh but without that bumpy, slow, and getting stuck feeling?
custom collision mesh thats better?
also split this into sections so you can use occlusion culling
Low hanging fruit here would be to stop hard coding the level names and keys.
Either use the scene name (directly or with a prefix/suffix) as the playerprefs key, or put a component in the scene that gives you the level name and use that.
Then you can stop duplicating the code for each level too. The code duplication is terrible.
deltaTime is how much time has elapsed since the last frame
if you want to get how much time has elapsed over multiple frames, you sum each frame's deltaTime
I've been thinking about that, whats holding me back is, the player model, im using a capsule collider right now and have foot IK "snapping" the feet to the ground, then I would need to layer the ray casts, that would be fine, but I somehow need to adjust the collider hight too otherwise the distance to the ground is too big making the foot float instead
It makes perfect sense to add it if you're adding up how much time has passed, like a timer as you said
https://gyazo.com/1cb0176e729fbb4288c4032269d64ffa I dont really know how I would combine everything like that
humm.. I see. but then how does Unity know I'm talking in seconds and not in frames when I'm building a timer?
here for example, how does Unity know 2 and 0 are seconds? the rest of the code doesn't seem to specify it in any way
good lord its up to YOU
if (quickReload.timerTime <= bestTime || bestTime == 0)
{
bestTime = PlayerPrefs.GetFloat(currentSceneName, bestTimeL1);
if (bestTimeL1 > 0)
{
timeSaved = bestTime - quickReload.timerTime;
TimeSaved.text = string.Format("- {0:F2}", timeSaved);
}
Invoke("BestTiemDelay", 0f);
}
somethin like this?
but HOW then
Time.deltaTime is seconds so if you use as is then its all seconds
well here we go
nothing about it says they're in seconds. if you treat them as seconds, then they're seconds
3 can be 3 seconds, 3 frames, 3 meters, 3 meters per second, etc
it's all up to how it's used
so in order to treat them as seconds, I need to add seconds to them?
Look up the documentation page if you need to know such information
https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
I have read this
no, if you want them to be seconds, you need to think of them as seconds
I understand that it might seem basic to you guys but it is not to me. I don't understand how UNITY can think of them as seconds
and use them accordingly
setting or adding a value? make sure it's in seconds
passing it as an argument to something else? make sure that thing expects seconds
unity does not
the language just does not have a concept of units
this exists entirely outside the code
float timerInSeconds = 0f;
void Update()
{
timerInSeconds += Time.deltaTime;
}
oh look its counting real time in seconds because the source value is the delta for that frame in seconds
this is how you treat a variable as seconds
float time;
Debug.Log($"time: {time} seconds");
it's all about how you, the developer, intend it
it does say "seconds" in the code, but that's inside the string. unity and c# don't care about that, that's for your eyes, the developer
the guy in the tutorial I'm watching did not specify any number. he simply wrote timer += timer + Time.deltaTime;
AND he said the timer would count 2 SECONDS until it resets
so how does this make any sense?
calm down, you're trying to find a link where there isn't one
he did write public foat spawnRate = 2 and private float timer = 0 but why would those be counted as seconds then
hahahaha I don't get it
float timerInSeconds = 0f;
void Update()
{
timerInSeconds += Time.deltaTime;
if(timerInSeconds >= 2f)
{
DoSpecialThing();
timerInSeconds = 0f;
}
}
unity is not sentient - it does not think about seconds
but then how does it count 2 SECONDS before it resets
Indeed. Its our logic that makes things happen when we want
if he didn't put in any math
Look at my example
Time.deltaTime is just some random number, but unity devs defined it to be seconds
so when you set a variable to that value, it is also in seconds
how do you send codes like that
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
when you compare it to other values, those are also in seconds (otherwise it wouldn't make sense)
what does f stand for here, frames?
no, it just means it's a float
its a float literal
'''cs
//buh
'''
the number 2 as a float
so this is what I said, it is because it is related to seconds (Time.deltaTime) that it ends up being seconds, right?
ok
Use `, not '
yeah
but another layer to that - Time.deltaTime is just in seconds because unity devs decided to have it in seconds
perhaps throw out "seconds" for a bit, you might be thinking too narrowly
If the game is running at 60fps then Update() is called 60 times a second and Time.deltaTime will be 0.016. 0.016 * 60 is? 1! (nearly)
yeah I get that
Then you should get why we use it to count time passing in this way
I just find it odd that simply relating a random number to something counted in seconds automatically makes it count as seconds
but if that's what it is that's fine I get it now
because your understanding is flawed, the value we are using is the frame DELTA
There is an alternate way to check for passed time that may make more sense to you:
float lastTime = Time.time;
void Update()
{
if(lastTime + 2f < Time.time)
{
DoSpecialThing();
lastTime = Time.time;
}
}
this does a thing every 2 seconds
Time.deltaTime is just some value, let's say it's 0.1
we could count Time.deltaTime over multiple frames, let's say we've gone through 15 frames so the total would be 1.5
that value, 1.5, doesn't mean anything on it's own. period. there is no inherent property that makes it count seconds
what do lastTime and Time.time stand for here?
the last frame and the current one?
We record the current Time.time value (which keeps track of time in seconds since the game was launched) and keep checking till atleast 2 seconds has passed. When this happens we do a thing and update the last time we did the thing.
This works because each Update() Time.time is different as its being advanced by unity for us
but you did say Unity makes this specific thing count as seconds, no?
you, as the developer, can interpret that value to have more meaning than just 1.5
we know Time.deltaTime is in seconds, because unity devs said so (and made it count as if it were in seconds, accordingly)
then when we count, because we're summing seconds, we know the result is also in seconds - so now we can apply meaning, that the value of 1.5 in this context means 1.5 seconds
yeah i probably shouldve sent these as a single message ^
oooooh yeah that just made it way more clear
he just never specificed that Time.deltaTime was counted as seconds tbh that's the key thing
-# 🤔
There's a timer example there that explains it
but 2 times 0.0something won't make 2 seconds would it now?
not sure where you got the "2 times" part from?
how does he end up with a 2 seconds timer
I just saw your reply and drew it on paper to check, you're right 😭 i've been torturing myself with this for 3 days now, thanks
well this
there's no multiplication there
hum you're right I messed that up
so timer is equals to timer + Time.deltaTime, but that doesn't equal to 2 seconds tho
because Time.deltaTime is in seconds, not frames
we are going in CIRCLES AAAAAA
Try out the examples and witness them work and deal with it
suppose a consistent deltaTime of 0.2 (aka 5 fps)```
frame 0: timer = 0.0
frame 1: timer = 0.0 + 0.2 = 0.2
frame 2: timer = 0.2 + 0.2 = 0.4
frame 3: timer = 0.4 + 0.2 = 0.6
frame 4: timer = 0.6 + 0.2 = 0.8
frame 5: timer = 0.8 + 0.2 = 1.0
I think I get it: it ends up being a 2 seconds timer because it says that until timer is at least equal to spawnRate, which is 2, then it will reset.
so spawnRate also ends up being counted as seconds in that situation?
note that the computer doesn't actually "know" anything. it simply performs the commands you give it
float lastTime;
void Update() {
float deltaTime = Time.time - lastTime;
Debug.Log($"{deltaTime} seconds elapsed");
lastTime = Time.time;
}
``````cs
float lastPosition;
void Update() {
float deltaPosition = transform.position.x - lastPosition;
Debug.Log($"{deltaPosition} meters traveled");
lastPosition = transform.position.x;
}
```these 2 snippets are equivalent if you just look at the numbers. we can analyze that the first is using seconds and the second is using meters because of what other values it's using - ones that are defined as those units
but sometimes you don't have values that have predefined units, you might specify those units yourself - and that's all in how you decide to treat them, not related to how it's written at all
yeah I think I get that
I'm just not fully sure about how it ends up being a 2 seconds timer, in relation to the spawnRate
spawnRate is just the number 2. It's what you're checking your stopwatch against. "Have 2 seconds passed yet?"
timer is like a stopwatch.
Time.deltaTime is in seconds and spawnRate is 2, so it happens to be 2 seconds
nothing about the logic thinks about seconds
so spawnRate will be treated as seconds too then?
because it couldn't define that timer is inferior or not to spawnRate otherwise
since there's no conversion factor, yeah
ok
you could have it checking against spawnRate * 60 and then it'd be treating spawnRate as minutes
it's all in relation to something then
it's usually thought of in the other way though

you decide that spawnRate is in seconds
almost there
then if you end up comparing spawnRate to a value in minutes, that's just a mistake - it doesn't redefine spawnRate
now last thing: I'm getting confused about how "timer = timer + Time.deltaTime;" doesn't end up being 0 = 0 + Time.deltaTime
the left side isn't 0
since we defined that timer is equal to 0 before
= is an assignment
it's setting the variable timer to be the value timer plus deltaTime
it is 0 + Time.deltaTime on the first frame
so how exactly does Unity treat the left timer as something to get value from the right part, instead of treating it as 0?
0 + .015 gives you 0.015
it doesn't
this is how c# works
The way = works in C# is that the thing on the left BECOMES the thing on the right
a = 5; makes a be 5
= takes the value of the right side and puts it into the variable on the left
it doesn't matter what a was before
just like how float timer = 0; was before
if you took the left side as a value that just wouldn't work, since timer didn't exist before that point
ooh ok that makes total sense
was missing this info
so this was a.. you didn't understand how = works in programming?
that's basic c#, so.. you're definitely in too deep for your level of understanding lol
why does the stuff in void Start() not carry over to the statement in void Update()?
Because when you declare a variable in a method it is local to that method only.
The place where you declare a variable determines the scope of that variable
configure your !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
• :question: Other/None
I got it mistaken
well now I understood everything!
so thank you guys, it felt like my dad screaming at me for not understanding math all over again but it was worth it
well why does this not work then?

@balmy vortex do this first.
Because you're making new variables inside of an if statement. Think of the { } as "walls". If you make something inside of it, nothing outside of it will know of its existence.
If you want variables which are accessible throughout your script, put them outside these functions, at the top (but inside your class)
To be more precise, when you declare a variable in a scope it is local to that scope only. Praetor was likely not wanting to introduce the concept of scopes to someone who hasn't even configured their IDE and is likely just starting
variables exist until they hit a }
Because I gave you a partial answer and in fact it's any scope that you declare the variable in that it's local to, not just methods.
Using {} defines scopes
Okay
Hello everyone. I have a material with shaderGraph shader which just outputs a simple noise. I want to render this material into renderTexture, but it is not working. I created a script which does
Graphics.Blit(null, renderTexture, material);
then I assign this texture to a RawImage to see results. Maybe I need to do something with UVs. How should I do rendering of custom material into square render texture?
Try normal UV input instead of screen pos.
And go to rendering to ask such questions
Wrong channel
Thanks!
thanks and sorry for wrong chanel
oh ok ty king
{
if (!IsGrounded)
{
return;
}
float time = 1;
while (time <= 1)
{
PlayerCamera.transform.localPosition = Vector3.Lerp(PlayerCamera.transform.localPosition, new Vector3(0, -0.346f, 0), time);
time -= Time.deltaTime;
Debug.Log(time);
}
}
why's it just snap directly to the bottom position
ignore the spacing discord messed it up
What's it supposed to do instead?
lerp between the current camera position and the new vector 3
Well, you're not doing proper linear interpolation so I would advise you first to consider that. Otherwise, this likely all happens instantly as it doesn't seem to be yielding control
Which it does. In one frame, because loops run to completion before anything else can happen
oh. how do i fix both those issues?
Depends.
Don't use a while loop and have the timer tick down in Update
what'd be the better way?
You should show more !code if you're wanting advice. Otherwise as suggested, process the lerp in Update without the loop
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
what do you mean by the last part? all i need to to transtiion a position ebtween two points
Right now, the function will complete the loop before exiting the function.
Start is called at the beginning of an object when a new scene is loaded, right?
called once after a monobehaviour is created and enabled
so that also happens to occur when a new scene opens
Oh right, but not really for a singleton
not relevent, if the component already had Start() called it wont happen again
Do not confuse the two
They run one time only, so the scene loading does not call Start on them
If you load a new scene, it will create gameobjects and their monobehaviours may then have Start() called because they are newly made
I get what u mean
If you move one of those gameobjects do dont destroy on load, start() will NOT be called on it again
The objects that have been marked to not be destroyed aren't being created in the new scene so they do not call Start. They had already called Start when they were created.
Uhm, I just said that
So there is that
If you understand then thats good case closed
I m fairly new to Shadergraph and I want to know if its possible to add text on a texture using Shadergraph?
hello,I have an issue in my gunsystem script, the player can shoot thru walls and still hit enemies, the WhatIsEnemy layer contains walls obstacles and enemies
if (Physics.Raycast(fpsCam.transform.position, direction, out rayHit, range, whatIsEnemy))
{
if (rayHit.collider.CompareTag("Enemy"))
{
rayHit.collider.GetComponent<Enemy>().TakeDamage(damage);
}
else
{
Instantiate(bulletHoleGraphic, rayHit.point, Quaternion.Euler(0, 180, 0));
}
}
Maybe you should check if a wall was hit first?
That would be quite difficult so don't bother. Use text mesh pro to show text somewhere
the RayHit doesn't stop the ray?
I went in holiday for 15 days and it looks like I've forget everything
Say what? Ray hit would be the object that was hit.
yes
It doesn't have anything to do with stopping a raycast.
the ray hits the wall first which is in the layer, so the RayHit basically is the wall
which would stop the ray?
from going further$
no?
Check if the wall has the same layer mask
they do
different layers but they both are referenced to the WhatIsEnemy variable
- !code
- Show where you define
whatIsEnemy - Show the inspector of the object you're expecting to block the raycast
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
At this point my assumption is that either the enemy object was hit before the wall because it was closer, the wall isn't on a layer to be hit or the layer mask isn't correct.
it's not closer, the enemy was like 100 meters behind the wall
You cropped the actual relevant bit out of this screenshot
🤦♂️
IM TOO DUMB, I created the layers, but didnt assign them to the walls and obstacles
This is why when someone asks you to check something you actually check it instead of just assuming you did it
which is also the reason the hit effects weren't appearing$
yes im sorry, I really thought I had assigned them tho,
When it'd take like two seconds to check, you should just check.
I have not left the house without my phone and wallet in like ten years but you can bet that I pat my pockets every single time I leave the house before I lock the door
yea, I know, thanks for your advice
Hey, I was under the impression these 2 were supposed to be the same, with the exception of the first one ignoring the mass of the rb:
_rb.AddRelativeTorque(new(_flipRotation, 0), ForceMode.VelocityChange);
_rb.AddRelativeTorque(new(_flipRotation, 0), ForceMode.Impulse);
However, I noticed that the VelocityChange one messes up the rotation occasionally, it just feels off and is sometimes a mirror of what it should be(I flip in the opposite direction).
Is this a bug or am I misunderstanding how this works?
Please @ me and thanks in advance!
To be precise it ignores the inertia tensor, (which is essentially rotational mass)
Flipping in the opposite direction might just be a result of going too far in one direction or reaching the limits of the maximum rotation rate. It's hard to say without being privy to the exact details here
Would be nice if there was a built in way to just ignore the mass tbh, guess I'll just stick to impulse and scale with mass :/
public IEnumerator StartSlide()
{
if (IsGrounded)
{
ElapsedTime = 0;
while (ElapsedTime < 0.1f)
{
PlayerCamera.transform.localPosition = Vector3.Lerp(PlayerCamera.transform.localPosition, new Vector3(0, -0.346f, 0), ElapsedTime/0.1f);
ElapsedTime += Time.deltaTime;
yield return null;
}
}
}
public IEnumerator EndSlide()
{
ElapsedTime = 0;
while (ElapsedTime < 0.1f)
{
PlayerCamera.transform.localPosition = Vector3.Lerp(PlayerCamera.transform.localPosition, new Vector3(0, 1.125f, 0), ElapsedTime/0.1f);
ElapsedTime += Time.deltaTime;
yield return null;
}
}
why does the players' view jitter up and down when the button is pressed quickly?
void OnSprint(InputValue Value)
{
if (Value.isPressed)
{
Debug.Log("Test");
PlayerFPController.StartCoroutine(PlayerFPController.StartSlide());
}
else if (!Value.isPressed)
{
PlayerFPController.StartCoroutine(PlayerFPController.EndSlide());
}
}
this is the input code
it's only when the button is seemingly pressed before the 0.1 second timer ends
the only "fix" i've found is stoppuing all coroutines in the input code, but that seems not the best, stopping the two coroutines individually doesn't work??? they're the only two coroutines.
Stopping them individually does work but it's very easy to do it incorrectly
i was just doing (simplifying bc im lzy)
stop coroutine (end slide)
stop coroutine (start slide)
i did this in the input code
for both released and pressed
You need to show what you actually did for us to tell what was wrong with it
that does work if you do it right
{
if (Value.isPressed)
{
PlayerFPController.StopCoroutine(PlayerFPController.EndSlide());
PlayerFPController.StopCoroutine(PlayerFPController.StartSlide());
Debug.Log("Test");
PlayerFPController.StartCoroutine(PlayerFPController.StartSlide());
}
else if (!Value.isPressed)
{
PlayerFPController.StopCoroutine(PlayerFPController.EndSlide());
PlayerFPController.StopCoroutine(PlayerFPController.StartSlide());
PlayerFPController.StartCoroutine(PlayerFPController.EndSlide());
}
}
i don't know why this wouln't work
You have to stop the same coroutine that you started, not a new one. See https://unity.huh.how/coroutines/stopcoroutine
aren't i alreasdy doing that? sorry if i seem dense
im making a boss battle and the boss instantiates a few minions
i made an observer pattern for the health, does anyone know how can i make each minion with their own event
No, every time you call StartSlide or EndSlide it starts a new coroutine
ohhh, how would i end them correctly then?
There are instructions in the link I posted
that works for the coruoutine i start in the if statement, but i'm not starting the other one, how would I do that?
is there a way to get running couroutines?
I don't quite get what you're asking
startcoroutine returns the coroutine value
check if the variable is null before calling stopcoroutine
{
Coroutine EndSlideCoroutine = null;
Coroutine StartSlideCoroutine = null;
if (Value.isPressed)
{
if (StartSlideCoroutine != null)
{
PlayerFPController.StopCoroutine(StartSlideCoroutine);
}
if (EndSlideCoroutine != null)
{
PlayerFPController.StopCoroutine(EndSlideCoroutine);
}
StartSlideCoroutine = PlayerFPController.StartCoroutine(PlayerFPController.StartSlide());
}
else if (!Value.isPressed)
{
if (StartSlideCoroutine != null)
{
PlayerFPController.StopCoroutine(StartSlideCoroutine);
}
if (EndSlideCoroutine != null)
{
PlayerFPController.StopCoroutine(EndSlideCoroutine);
}
EndSlideCoroutine = PlayerFPController.StartCoroutine(PlayerFPController.EndSlide());
}
}```
like this? it still doesn't work
Local variables cease to exist when the function ends
well no because those are local variables that disappear right after the function ends (and even if they didn't they're set to null at the start, removing any coroutine that might be stored there)
So you press sprint, you set those Coroutine variables to null
So you are calling StopCoroutine on a null
make class fields (private Coroutine EndSlideCoroutine;) outside the function
i made it public and now it works :) thaks
one more think, when going down slopes do character controllers by default increase in speed or do i need to make that?
Depends how much you want to increase the speed, the simple ones usually go faster in relation to the slope because the vertical velocity stays the same
(but not noticeably)
Awake() should be called first time even when an object is inactive, right?
oh i meant the component
if the object starts inactive, it'll be called when the object becomes active for the first time
(if that doesn't answer your question, could you clarify? im not quite sure what you're asking)
You have to code the movement to that yourself anyway so in that sense you do need to make it
any advice to where to startt witht hat?
Hi, I bought Harrison Ferrone's book "Learning C# by Developing Games with Unity". Has anyone read it?
If you're looking for a specific recommendation then it's probably too late since you already bought it.
If you have a question about it you should probably just ask it
I have this script where when I press esc the game should pause and the cursor should show and when you un pause it shouldn't show. the pausing works but the cursor doesn't show at all in the build version nor does it really work in the editor am I doing something wrong?
Is there anywere else in your code that the cursor state is being changed?
yes in my fps controller I have this
and when is this called?
I'm calling it in update
should I just reference the lockCursor bool from my fpsController?
Why not just change the bool lockCursor in the fps controller in the MainMenu class instead of trying to change the values again
Yeah
i had some similar problem .. try switching the positions.. first the visibility then the lockstate..
Well i doubt this is it their MainMenu class only changes the Cursor states once but the fps controller is changing it once per frame so the minute it's changed if the fps controller bool is set to true it will never show
yeah probably.. but as said i had some similar problem w a while ago.. it fixed my problem just swapping them around...
@rough granite I decided to do it this way https://paste.ofcode.org/EnBZQT6rtZsyv5UH84EKta and it works but when I unpause the game how would I make the cursor disappear? I have to click to make it disappear
I think I am just going to let the main menu script handle hiding/showing the cursor
No sure :/
if I want a character that's physics based (sliding, wall jumping ect.) is it Really best to use a character controloler? is there another component or plugin that has more stuff built uin like godot's or is this really the best wy
there is the rigidbody
isn'
t that
not reccomended for players
or is it fine
yes it is fine..
the best way is to make a kinematic character controller
and yes there are ready made ones with a bunch of functionality built in, on the asset store for example
kinematic character controller?
yes
what's that?
here's one https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
i cant guarantee that this is the best one tho
Hello 🙂 i made this scriptable object but i would like to know how can i get this data in my script ?
You make a serialized reference like a public float that you fill out in the inspector
i know but how can i get these value in my other monobehaviour script ?
Again, get a reference to the object and use the reference
Ohhhh like public ScriptableObject wood; ?
You would use the type that your SO actually is rather than the type ScriptableObject
In this case, Item
public Item wood; ?
No it's called Item
should ı make my inventory system on a dont destroy on load gamemanager object to save it
No, the smarter thing would be to use a separate scene to hold objects that should persist throughout the game.
And then load your gameplay scenes asynchronously. That way your Root scene (or whatever you call it) that contains your inventory object and any other managers for that matter, will also be available.
my boss from the game im doing spawns some minions, in the health script because i used an observer pattern i need an event, and each minion needs their own, how can i every time that a minion spawns give their own events?
Hi, I am following the Junior Programmer Pathway, and I am stuck at "Lab 3 - Player Control". There is no Project Files to download, anyone know where I can get them?
Doesn't look like you need to? Seems that you're supposed to make the project from scratch
Oh, that explains it 🙂
Hello again 🙂 i would like to change My image sprite but i think i dont get the component correctly. someone know what is wrong ? Icon = gameObject.GetComponentInChildren<Image>(); txt = gameObject.GetComponentInChildren<TextMeshPro>(); Icon.sourceImage = sprite;
create direct references instead of doing this mess
but i will have to make this reference in every slots 🥲
does something to get a child by his name exist ?
This is why UI like this gets built by code and why each "slot" should use its own component to ref the image and text
use layout groups to do horizontal/vertical/grid layout automatically
No way exist to get my image component from my child ??
Yea what you did works but its not great
currently you need something like
foreach(GameObject slot in slots)
{
slot.GetComponentInChildren<Image>().sprite = blah;
}
better to have
foreach(Slot slot in slots)
{
slot.image.sprite = blah;
}
So, for my unity pathway personal project, I wanted to make a game where you destroy cubes by jumping on the top of them, the problem I'm having though is that I don't think I've actually been taught any way to move a 3d shape towards the player other than addForce, which just seems to make the blocks very "slippy"
the script i am making will be in every slots so i dont have to do this ?
yea you can make a new script called "Slot" to let you reference the image and text of each slot easier!
then have a serialized List<Slot> slots
I made this to get my child but it dont change the picture and the text 🥲
public int id;
public string Name;
public Sprite sprite;
private Image Icon;
private TextMeshPro txt;
private GameObject logo;
void Awake()
{
logo = gameObject.transform.Find("Icon").gameObject;
Icon = logo.GetComponent<Image>();
txt = gameObject.GetComponentInChildren<TextMeshPro>();
}
void Start()
{
ReloadSlot();
}
// Update is called once per frame
void Update()
{
}
public void ReloadSlot()
{
txt.SetText("x" + numb.ToString());
Icon.sprite = sprite;
}```
is this script on each of your Slots
i tried to put it on only one but yes it is supposed to be on every slots
If its on the prefab it will be on each
second use [SerializedField] instead of find and GetComponent
the you can just drag both in via the inspector ui
ok i will try
Hmm, I got it to not be slippy with transform.Translate, now I have the problem that it's ignoring that Ifroze it's Y axis, so now it's flying and even sinking into the ground somehow
If you're moving a Rigidbody via the Transform you're doing it wrong
Would it work if I just transformed the object itself?
which object? Isn't that what you're doing?
You should back up and explain what you're trying to accomplish exactly
I said it here
you could just set its velocity directly
if you don't want to deal with realistic momentum
The problem is, the pathway course is asking me to design how enemies move while only having taught me transform.Traslate and AddForce
And I dont think either are great for my idea
they are not
I'm telling you a better alternative
note that what you want is possible with AddForce it would just require more complex calculations than what you are probably interested in performing
and it would be simpler to just set the velocity directly
you can use Rigidbody.MovePosition() instead which will do velocity changes for you
Do what it says
I don't recommend this
MovePosition doesn't respect collisions
There's no good reason to use it over velocity here
It's really for kinematic bodies
It does because its still uses velocity to move
but you will keep pushing into things
not what I have observed 🤔
oh shit is 3d and 2d different
ffs unity
my mistake I used the 2d version last
So how would I use linear velocity to make it move towards the player
set the velocity to something to go towards some position
Vector3 dir = target - self; (not normalized)
rb.linearVelocity = dir.normalized * multiplier
Nice, that actually works
you may wish to clamp the magnitude of the new velocity using Vector3.ClampMagnitude() but should mostly work
What would that accomplish? I haven't had to deal with clamp yet
Could anyone point me in the right direction here?
I'm looking to create an inventory system, and there will be some pre-existing items that the player can add to their inventory.
However, I need to create an item system that allows to the player to create items with custom values and descriptions. I'm assuming that I'll be using structs, but beyond there I don't really know where to start. Can someone point me in the right direction?
Actually ignore me in this situation the speed it moves at is consistent as we normalise the dir vector
If we omitted that then we would wish to clamp magnitude
Ah yeah, my look direction is normalized
void Update()
{
Vector3 lookDirection = (player.transform.position - transform.position).normalized;
enemyRb.linearVelocity = lookDirection * speed;
}```
(Not that I actually understand what that does)
You can use structs or classes, sure.
.make a struct or class that describes an item, and make a way to:
- display them in an inventory
- create them as a player
is there any smart way to make my 2d sprite blink repeatedly? (this is for when taking damage)
this is the method i could think of and i know it looks stupid
IEnumerator TakingDamage()
{
while(takingDamage)
{
invincible = true
defaultSprite.SetActive(ture);// ---------
yield return new WaitForSeconds(0.5f);//-- this 4 lines repeat 3 times
defaultSprite.SetActive(flase); //-------- not pasting them all out
yield return new WaitForSeconds(0.5f);//-- cuz i dont want to clog the chat
invincible = false
takingDamge = false
}
}
Use a loop
I just don't want to start and find out that whatever I do will make it impossible for a player to do the same. Are there any risks there?
Never repeat code like this
You really need to start trying stuff. I'm not really sure what risk you're worried about. Design it with the object being created at runtime in mind that's all
normalizing a vector changes its length or magnitude to be 1
le google
thanks! i forgot loop is a thing
Yeah, thats the jargon answer though. I don't really understand what that means in a practical sense so I dunno how and when to implement it
It's only jargon if you don't understand what the magnitude of a vector is
It's just the length of the line
google will define all these terms for you
and are important to learn for working with 3d vector maths
The point of it is to have a vector that can easily be multiplied by something (such as the speed here) to get a vector with a desired magnitude since a magnitude of 1 is the multiplicative identity value
It's all over my head atm
What it means in the practical sense is that it makes the length of the vector 1. You use it when you want the length of the vector to be 1
I'm still very beginner
well when getting a direction vector its best to normalise so it makes things consistent and not change based on the distance
(unless we desire such an effect)
void Update()
{
Vector3 target = Player.transform.position - transform.position;
if (enemyState == STATE.Aiming)
{
Aiming(target);
}
else if (enemyState == STATE.Dashing)
{
Dashing(target);
}
}
void Dashing(Vector3 target)
{
//logic to dashing will be implemented later
transform.Translate(3f * Time.deltaTime, 0, 0);
}
private enum STATE
{
Aiming = 0,
Loading = 1,
Dashing = 2,
}
void Aiming(Vector3 target)
{
//Keep looking at the player.
float angle = Mathf.Atan2(target.x, target.z) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, angle, 0);
StartCoroutine(waitToChangeState(3f, STATE.Dashing));
}
IEnumerator waitToChangeState(float delay, STATE state)
{
yield return new WaitForSeconds(delay);
enemyState = state;
}```
Hey guys I want to change the enemy state based on a delay, and this is what I came up with. I don't know if the repeated calling of (StartCoroutine(waitToChangeState(3f, STATE.Dashing));)
Will cause a problem?
Is there a better way to change states on a timer?
yes it's going to cause a problem, you're starting a new coroutine every frame
yeah I felt that would be the case
that seems like a coroutine you only would want to start when you first enter the aiming state
in the case of this script it seems like maybe in Start
Thing is, I will enter the aiming state again.
I haven't written it yet but after dashing, it's going to return to Aiming state
And it's supposed to go back and forth
Dash and Aim, Dash and Aim
right that doesn't change my answer
you would start the coroutines when you enter the states
it might make your code cleaner to make a function for entering a state
instead of just calling:
enemyState = state;
you woul do:
ChangeState(state);```
in ChangeState you might have a switch:
void ChangeState(STATE newState) {
enemyState = newState;
switch(newState) {
case STATE.Dashing:
StartCoroutine(waitToChangeState(3f, State.Aiming));
break;
case STATE.Aiming:
StartCoroutine(waitToChangeState(3f, State.Dashing));
break;
}
}```
something like this
you can put whatever behavior you need in this switch, to handle what needs to happen when you first enter any given state
Simple example here for having them sort of "pingpong" with each other^
but still extensible for other states
perhaps the switch() is confusing for such an example
So where would the function call be?
If I call it within the functions Aiming() and Dashing() wouldn't it still create a Coroutine every time?
If I call it in Start how can I call it again?
So where would the function call be?
Every place where you change the state
If I call it within the functions Aiming() and Dashing() wouldn't it still create a Coroutine every time?
That's not where you're changing the state
If I call it in Start how can I call it again?
There's nothing that prevents you from calling it in multiple places
The only place you're currently changing the state is here:
IEnumerator waitToChangeState(float delay, STATE state)
{
yield return new WaitForSeconds(delay);
enemyState = state;
}```
so that's the only place you would put the call to the ChangeState function to replace what you have now
However you also need to put it in Start
to kick things off
Oh yeah I get it now thanks
it's going to recursive call through the Coroutine of waitToChangeState
yes
yeah thats a lot better thanks for helping
Hello again 🥲 i always get this error when i try to do the function addItem() i am trying to fix the bug but i dont find where is the problem.public void AddItem(int itemID, int amountToAdd) { slotVerified = 0; for (int i = 0; i < slot.Length; i++) { if (slotTakenID[0] != itemID) { slotVerified += amountToAdd; } else { avalaibleSlot = i; } } if (slotVerified != slot.Length && item[avalaibleSlot].stackable == true) { scriptSlot[avalaibleSlot].numb++; } else if (slotVerified == slot.Length) { for (int j = 0; j < slot.Length; j++) { if (slotTaken[j] == false) { slotTaken[j] = true; slotTakenID[j] = itemID; scriptSlot[j].numb += amountToAdd; scriptSlot[j].Name = item[itemID].Name; scriptSlot[j].sprite = item[itemID].sprite; scriptSlot[j].taken = true; scriptSlot[j].ReloadSlot(); break; } } } } if (Input.GetKeyDown(KeyCode.E)) { inv.AddItem(0, 1); } if (Input.GetKeyDown(KeyCode.A)) { inv.AddItem(1, 1); } if (Input.GetKeyDown(KeyCode.F)) { inv.AddItem(2,1); }
Based on my reading I thought I didn't need to have a yield return line in my SceneRedirect method. However I am getting compiling errors "not all code paths return a value". Any thoughts?
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Threading.Tasks;
using System.Collections;
using System;
public class InitScript : MonoBehaviour
{
public GameObject logo;
private Renderer logoRenderer;
public float AnimationSpeed = .25f;
private void Awake()
{
logoRenderer = logo.GetComponent<Renderer>();
}
void Start()
{
StartCoroutine(AnimationSequence());
}
private IEnumerator AnimationSequence()
{
yield return StartCoroutine(AnimationLogo());
yield return StartCoroutine(SceneRedirect());
}
private IEnumerator AnimationLogo()
{
float dissolveCurrent = 0.8f;
while (dissolveCurrent >= 0)
{
dissolveCurrent -= AnimationSpeed;
logoRenderer.material.SetFloat("Stage", dissolveCurrent);
yield return null;
}
}
private IEnumerator SceneRedirect()
{
//SceneManager.LoadScene("Scenes/Intro/Loading/Loading");
Debug.Log(AnimationSpeed);
// yield break; comment out causes error
}
}
there's absolutely no reason to use a coroutine if there is no yield in it
ah ok. Just just call SceneRedirect at the end of AnimationSequence. That makes sense. I knew something was up.
yeah just make the return type void
thanks. I appreciate it.
What line is the one the error is on?
Unity talk about cs.38 so this one ```` if (slotTakenID[0] != itemID)```
Then it would seem that slotTakenID is null
i tried to set slotTakenID at -1 but i still have the same error
What do you mean "set it at -1"? It appears to be a list of some kind
you can't set a collection to -1
it is an int array why it cant be -1 ? for (int i = 0; i < slot.Length; i++) { scriptSlot[i] = slot[i].GetComponent<slotScript>(); slotTakenID[i] = -1; }
Because an int array is not an int
A bag of potato chips is not made of potato
Your array is null
Don't try to use null as if it were an array
Where do you assign a value to slotTakenID?
you have to initialize your array
public GameObject[] slot;
private int[] slotTakenID;
private bool[] slotTaken;
private int slotVerified;
private int avalaibleSlot;
private slotScript[] scriptSlot;
void Awake()
{
int[] slotTakenID = new int[slot.Length];
bool[] slotTaken = new bool[slot.Length];
slotScript[] scriptSlot = new slotScript[slot.Length];
for (int i = 0; i < slot.Length; i++)
{
scriptSlot[i] = slot[i].GetComponent<slotScript>();
slotTakenID[i] = -1;
}
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void AddItem(int itemID, int amountToAdd)
{
slotVerified = 0;
for (int i = 0; i < slot.Length; i++)
{
if (slotTakenID[i] != itemID)
{
slotVerified += amountToAdd;
}
else
{
avalaibleSlot = i;
}
}
if (slotVerified != slot.Length && item[avalaibleSlot].stackable == true)
{
scriptSlot[avalaibleSlot].numb++;
}
else if (slotVerified == slot.Length)
{
for (int j = 0; j < slot.Length; j++)
{
if (slotTaken[j] == false)
{
slotTaken[j] = true;
slotTakenID[j] = itemID;
scriptSlot[j].numb += amountToAdd;
scriptSlot[j].Name = item[itemID].Name;
scriptSlot[j].sprite = item[itemID].sprite;
scriptSlot[j].taken = true;
scriptSlot[j].ReloadSlot();
break;
}
}
}
}```
my array get his value only at the end of additem()
In Awake you create a new variable, also named slotTakenID, and create an array for that. The variable then ceases to exist at the end of the function
You probably want to use the one you've defined as a private variable instead
man kudos to your eyes, i couldnt find what was wrong 😄
as a sidenote, have you done !ide ?
It should warn you about overriding properties
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
oh you mean i only created the array for awake() but dont exist for addItem() ?
in awake your are using a local variable instead of your property
oh
bool[] slotTaken = new bool[slot.Length];```
i did this to set the size of my array but i suppose this is this who make this bug ?
CHAT GPT wtf i wonder if this works im not a programmer so I have no clue if this code is viable or not like damn im hapy for you chat gpt
Chat GPT
Probably doesn't
You need that code, but you need to not be creating a new variable
You need to use the one you already have
When you do [type] [name] = [value] that creates a new variable
If you want to assign a value to an existing variable, it's just [name] = [value]
not suprised but i do want to install unity and do it rq
Go ahead but you're probably not gonna get anyone here to want to debug the slop so you're on your own
im not here tryna develope no game 🥀
why not just learn how to do it properly ? so you know what the code is actually doing incase it most definitely will break
slotTaken = new bool[slot.Length];
scriptSlot = new slotScript[slot.Length];``` ?
i only play guitar 😭
guitar is fun 🙂
Over the past few weeks, I’ve been developing an XR Grab Interactable system for my VR guns. My goal is to make it so that if the player grabs near the trigger, the gun will use a preset attach point rather than dynamic attachment, while still allowing the rest of the gun to use dynamic attachment. I’ve tried a few approaches, but so far none have worked as intended. I’m now looking for advice on the best way to achieve this.
What does the new unity input system do and how do you even use it
I'm getting an error on line 9
using UnityEngine;
public class SetupManager : MonoBehaviour
{
[SerializeField] private GameObject[] playerItems;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
for (int i = 0; i < GameData.players.Count; i++)
{
playerItems[i].SetActive(true);
/*PlayerSetupDataMono playerSetup = playerItems[i].GetComponent<PlayerSetupDataMono>();
if (playerSetup != null)
{
playerSetup.playerNumber = i + 1;
}*/
}
}
// Update is called once per frame
void Update()
{
}
}
screenshot attached
oh yeah heres the error ```NullReferenceException: Object reference not set to an instance of an object
SetupManager.Start () (at Assets/Scripts/SetupManager.cs:9)
Assuming it's this line:
for (int i = 0; i < GameData.players.Count; i++)
Then GameData.players is null
make sure it's assigned before you try to use it
ohhhh ok alr
- It gives you an API to handle user input
- https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/manual/QuickStartGuide.html
alr thx it works now
So I'm being really stupid: I'm struggling with references. I was using static variables, and I realize that was stupid. I'm trying to backtrack.
levelDropCTRL = GameObject.FindGameObjectWithTag("LVL").GetComponent<LevelDropCTRL>();
I'm not sure how to make normal, non-static variables accessible like I did when they were static.
I was able to do stuff like this:
anotherconMod = AbilityScores.conMod;
you talking about public fields/properties?
using the class name is only possible for static members
otherwise its used on a class instance
I have public integers that I need to access. They were originally static because it seemed easier to access those values.
You need to GetComponent to one particular instance of that class
Then you'll have access to public variables inside that instance
This to me shows a lack of understanding of object oriented programming. Best read up on c# basics and c# classes.
Yeah it would show you that
Some things can be static but depends on the field/method
public class Player
{
public int health;
private int maxHealth;
}
public class SomethingElse : MonoBehaviour
{
public Player onePlayer;
void Start()
{
onePlayer = GameObject.FindObjectsOfType(Player).GetComponent<Player>();
onePlayer.health += 1;
}
}
This shoud work I believe
Static variables are a singular instance in the software IIRC
good lord no that wont
lol really? am I forgeting something?
many things 😆
So why could I do this with static variables but not with normal variables?
Well I tend to GetComponents only on self of set them through the inspector
It was so much easier when I could just reference the tagged object, and pull variables from every script on that object
Ah right I forgot to set a value for int lmao
static things do not exist on a class instance so are access using the class name
That can be "easier" but depending on its task that may be the wrong way to do things
public class Player : MonoBehaviour
{
public static Player Instance;
void Awake()
{
Instance = this;
}
}
Singleton pattern
You can make the object public and set the reference through the inspector, do you know how to do that?
a static field to let us access a player instance
If you do you can access public variables from that component by calling the reference name
learn more: https://unity.huh.how/references/singletons
Yeah I guess I could do that
public class Player
{
public int health = 0;
private int maxHealth = 10;
}
public class SomethingElse : MonoBehaviour
{
public Player onePlayer;
void Start()
{
onePlayer = FindAnyObjectByType<Player>();
onePlayer.health += 1;
}
}
Try this, I think it should work now
Btw the "FindStuff" in Unity is not a very good way of doing stuff, it should only be used in small projects/quick prototyping
In that example maxHealth wont be accessible because it's private, obviously
pretty sure you can only Find() unity objects
Yeah the provided code wouldn't work
FindAnyObjectByType<Instantiator>()
I'm using this right now in my prototype and it's working
yea its a monobehaviour i bet
Yes
have a good read what Player is 🤔
anyway this doesnt help with what they should actually learn
Ideally c# is understood well outside of the context of unity
Well, he seems to be interested in using Unity, not plain C#
Did you manage to make it work?
I'm blundering through. I'll probably get there eventually
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Just keep in mind these "Find" methods in Unity are just placeholder, you should be Getting Components on self, through the inspector or setting them directly to the desired thing
you can always use unity without c# once you're familar with unity itself and you need to use c# learn it then
Learning about c# lang concepts is always helpful. the microsoft docs are helpful and detailed
idk programming at all, but I'm wanting to learn. so starting with unity without it is more easier to not be overwhelmed. there's multiple ways to do things in unity without the use of c#, learn it step by step, you're just now learning you're suppose to make mistakes and not understand certain things.
You can get buy but there will come a point where the lack of understanding of OO programming will fuck you over
I was lucky I already knew java and c#
Knowing that components are instances and how GC works helps with many things down the line
gotta start somewhere 🤷🏽
Wait you can say swear words here? Nice
I don't know how I didn't find this video. Thank you.
@grand snow I understand that if everyone put an incredible amount of time into learning all aspects of Unity and C# from one course, they wouldn't be in my position. So I apologize for that.
There was a time where I knew how to do that. A few summers off and it all goes away.
no need to apologise, just important to know that you can learn about c# and about unity and to not presume learning about unity will teach you programming too.
its like going to unreal and expecting to learn c++ (you wont)
I mean truly idk unity at all, either I'm a beginner in all of this stuff so my question is How much can you get away with visual scripting vs c# anyways?
I really should try to learn more c#. Like I said, I'm not a programmer nor even proficient in Unity.
I spend two hours today basking in my own stupidity trying to figure out why
Public float float;
float = int/4
Debug.Log(float);
my float refused to give me decimals. f.
You can try asking some of these questions to an AI, like ChatGPT, sometimes you're forgetting something simple and the AI can quickly point it out to you.
Its how it works, 4 is an int literal but 4u is an uint literal ect
Why are we suggesting ai here?
I have done that a few times. GPT really doesn't understand referencing.
there are ways to define a literal of other types!
🙏 plz do not ask AI
It doesn't understand anything it's stupid no matter how much resources into training it
That is an ignorant and emotional position to take. There are many things that LLMs are capable of doing.
It's useful sometimes
for a beginner to learn, id say no
for someone with knowledge already, yes (as you can better tell when it makes up shit)
I feel like I was successful in picking up on what the shit was, but that's only because it contradicts itself.
it contradicts itself to make you the user feel good
Btw I'm not saying for people to blindly throw code at an AI and ask what's wrong, you can past small snipets of code, but it's better for you to analyze your problems and actually ask the AI for advice, if it doesn't work it won't work, then you can seek help with others
If you mean that it is often pressured into lying to you to avoid contradicting you, this is true.
But in these instances, that didn't apply. It would tell me one thing in one chat, and another in another chat.
and im gonna stay by it all it is a huge tree of weighted values that change bit value based off other similar crap.
Why would you insist your broken code is working though?
You need to know HOW to prompt the AI too
i meant in general not for coding you can ask it if god exists then say the opposite opinion and it'll changes it's opinion to agree with yourself

I'm talking about using AI to help solve problems
Also AI is almost a Google on steroids, you can also find stuff that you saw once in your life by telling it some vague descriptions and it can find it, pretty impressive
at this point, kinda wish ai was never created and people just learned how to google shit and use stackoverflow or seek others for help but we're getting off topic of the channel, but that's my 2 cents.
i admit, I'm guilty of using it but I've disciplined myself not to rely on it and do my own research overall
I always go to docs first when looking up something for a language or lib
I ask AI as a last resort but the vague shit I ask about often gives a made up answer so 🤷♂️
Now if we get started talking about integrating MCPs with it that might be a whole different conversation
When using lerp is using the animation curve better to go about doing this than using time.deltatime?
Integrating the animation curve with lerp is peak. You give yourself a custom curve—basically an easing function . . .
that's the only way I use lerp . . .
I know, I've seen videos about it and I'm excited to try just wanted to make sure lol.
But we were talking about the usefulness of AI in coding. I think you got distracted.
😭
Dude I'm going insane
I have all but one reference working
And there are no compiling errors, and I can't see anything wrong with the code
Ah my dumbass forgot to put in the renamed gameobject to the button controller. :}
Debug
Why does the GameObject being renamed matter?
Misspoke. I made a new game object and renamed it, and disconnected the old one. I then swiftly forgot to reconnect the new one
https://discord.com/channels/489222168727519232/1405710251608637511
So uh, problems again. Who's surprised? This time it's a pathing issue with files though.
Hello, I have a question about cooldowns
Would this be "safe" from frame hitches ? I dont want to have longer attack intervals then what is set
```c#
public void AttackFromTransform(Transform ownerTransform)
{
if (weaponType?.attackProfile == null) return;
cooldown -= Time.deltaTime;
if (cooldown > 0f) return;
Debug.Log(cooldown);
weaponType.attackProfile.Attack(ownerTransform, firePoint, this);
cooldown = parameters.attackInterval;
}```
What do you mean by frame hitches?
like a "long" frame from low fps. idk if its something to really worry about, chatpgt mentioned it when i was asking if there was any possible bugs here.
Current, if a minute or two passed because of the game freezing you'll only get one attack and your attack cooldown will be set back to your interval value
ah okay so ill just accumulate the time and not reset completely to fix?
ChatGPT is dumb lol
If you're wanting all attacks to be simulated.. you could do something like.. cs while (cooldown < 0f)//Replaces your if-statement { Debug.Log(...); weapon.attackPro... cooldown += parameters.attackInterval; }
ah okay, this is what chatgpt recommended.
is this common practice?
is this called per frame?
yes. cooldown is a member of a "Weapon" class. my actor calls this method in its update method
So I have code thats supposed to prevent you from not being able to reach the red square, but for some reason my rooms overlap with themselves, if you think you might be able to help me tell me and I'll DM you the code
No dms
I’m just desperate cause I’ve been trying for 7 hours today to fix it
is weaponType a unity object? if so you shouldnt use ?. on it
usually you would just do as dalphat said and use cooldown += parameters.attackInterval so you are still keeping those extra extremely small values like if cooldown is currently -0.05
so you worry less, there is a max delta time anyways which defaults to 0.3 seconds. if your game freezes for 1-2 seconds, deltaTime will still be 0.3. i wouldnt worry about designing around massive hitches because you shouldnt have massive hitches in the first place. there would 100% be other bugs out of your control if the game could progress seconds at a time
im just checking out r3 and i have no idea whats a reactive value is, anyone got basic an example or something for this in unity ?
thanks for the details
and yes it is a unity object, why should i not use ?. on it? is there some issues it can cause?
https://docs.unity3d.com/ScriptReference/Object.html
The null-conditional operator (?.) and the null-coalescing operator (??) are not supported with Unity Objects because they cannot be overridden to treat detached objects objects the same as null. It is only safe to use those operators in your scripts if there is certainty that the objects being checked are never in a detached state.
😮 ty, i wasnt aware of this. im new to unity. The little bits of info like this are appreciated
Then make a thread and ask for help there no one here that can properly help is willing to chat in dms
Broken random dungeon generation
Does anyone know any way for object to do certain tasks even if they start and stay inactive?
You can call methods on an inactive GameObject as long as you have its reference. Only Update methods aren't called when inactive . . .
I don't mean to call methods from inactive objects. I mean to get the inactive object do its own thing
Because getting references from a bunch of them is requiring me to fetch each object at a time in a loop, causing a delay at scene loaded
perhaps don't use Find or whatever then, use serialized references if possible, or if they're created at runtime, get whatever is spawning them to keep their references
Hi, how do I make the the gameobjects projected from the camera to game view, to be also projected to the canvas in scene view?
Do someone know that why Free Look is working fine for Up and Down but not for Left and Right?:
private void Awake()
{
//Cursor.lockState = CursorLockMode.Locked;
//Cursor.visible = false;
player = GetComponent<Rigidbody>();
mobileInputs = new PlayerMobileControlsInputs();
mobileInputs.Player.Enable();
// Look input binding
mobileInputs.Player.Look.performed += ctx => lookInput = ctx.ReadValue<Vector2>();
mobileInputs.Player.Look.canceled += ctx => lookInput = Vector2.zero;
// Free Look input binding
mobileInputs.Player.FreeLook.performed += ctx => isFreeLooking = ctx.ReadValueAsButton();
mobileInputs.Player.FreeLook.canceled += ctx => isFreeLooking = false;
}
private void Update()
{
// Camera rotation (Y for player, X for up/down)
float mouseX = lookInput.x * lookSensitivity;
float mouseY = lookInput.y * lookSensitivity;
rotationX -= mouseY;
rotationX = Mathf.Clamp(rotationX, -80f, 80f); // prevent flipping
cameraHolder.localRotation = Quaternion.Euler(rotationX, 0f, 0f);
if(isFreeLooking)
{
// Free Look to rotate cameraHolder only
cameraHolder.Rotate(Vector3.up * mouseX);
//cameraHolder.Rotate(Vector3.left * mouseY);
}
else
{
// Normal Look to rotate player
transform.Rotate(Vector3.up * mouseX);
}
}
private void FixedUpdate()
{
Vector2 moveInputs = mobileInputs.Player.Move.ReadValue<Vector2>();
float speed = 2.0f;
// Move in direction relative to camera's forward/right
Vector3 moveDirection = cameraHolder.forward * moveInputs.y + cameraHolder.right * moveInputs.x;
moveDirection.y = 0f;
player.linearVelocity = new Vector3(moveDirection.x * speed, player.linearVelocity.y, moveDirection.z * speed);
}
can't just move the holder + camera to be on size with the canvas since it relies on keyframing on absolute coordinates
Hey all. I ran into one of those unused variable warnings on a catch exception (DOTS/ECS workflow with burst). Made no sense to me since debug is using it. My brain sometimes does this thing where it screams at me... it's my intuition. Something creeps up from the depths of my memory and, usually, triggers an out of the box answer... This time it was, "discard your hand, ex, and draw another." Now, that is not exactly what is going on here... but I think you will get the picture as this is how I handled it:
catch (Exception ex)
{
#if !BURST_COMPILE
Debug.LogError($"GPU heightmap generation failed: {ex.Message}");
_ = ex; // Prevent unused variable warning
#endif
_ = ex; // Prevent unused variable warning
return null;
}
The first discard silences the debug variable warning and the second silences the Burst warning.
The real solution would be to do catch(Exception) for burst.
My understanding is that catch exceptions cannot be used inside of a burst block and that is why I used the #if !BURST_COMPILE but this works as well because it's not utilizing Burst in the method so it is safe. But I still discard after to silence the IDE.
// Managed method: safe to use exceptions. No BURST guards needed here.
private RenderTexture GenerateHeightmapGPU(TerrainGenerationData terrainData)
{
//...previous code
catch (Exception ex)
{
Debug.LogError($"GPU heightmap generation failed: {ex.Message}");
_ = ex; // LDL: Discard(ex) glyph to appease analyzers
return null;
}
}
My suggestion is to have 2 catch blocks, one for burst and one not to solve the issue without using discard
Tried it. Still got an IDE warning on Rider, VS, and VSCode. So... not sure why that would be unless catch is not allowed in a burst block.
your ide has no idea what burst is and id expect an error to be printed in unity if its not fully compatible with burst
No idea if exceptions even exist in burst code
#if BURST_COMPILE
catch(Exception)
{
return null;
}
#else
catch(Exception e)
{
}
#endif
does this work?
Does anybody know is it possible to implement asset picking from asset bundles by implementing a custom SearchProvider?
I want to make an SDK that ships a Unity project in which you work with original assets packed in a form of asset bundles, but at the same time I need to somehow support native workflow of using these assets in a project as if they were in your AssetDatabase
The only thing that I could find in regards to this is to create a custom SearchProvider, which is supposed to be what I am looking for but I feel like there is some caveat that I am not seeing
It took a bit of work, as it was being incredibly picky. This version of yours works without IDE warnings or errors.
#if BURST_COMPILE
catch (Exception)
{
// Burst jobs can’t throw – bail to safe default
return null; // must match RenderTexture return type
}
#else
catch (Exception ex)
{
Debug.LogError($"GPU heightmap generation failed: {ex.Message}");
_ = ex; // LDL discard glyph
return null;
}
#endif
If I do not discard I get the error. Every time. Whether a catch block or burst or not.
well we can clearly see that ex is used so that doesn't make sense
As I said in the OP. lol. It is used, but I have to discard it anyway.
Does anyone know how to stop stuff from clipping into eachother like this?
kk thanks
how do I actually convert my current code (https://paste.mod.gg/rapaytpkirqx/0) to use that though?
A tool for sharing your source code with the world!
cuz like rn I need to change the actual direction of every input since the camera rotates
a common way is to change the rigidbody velocity to move or using AddForce()
see similar convo yesterday: #💻┃code-beginner message
btw, if you have a rigidbody you should just not modify the transform at all and let the rigidbody manage it
just as a general tip
Currently my character uses W, A, S, D keys to move and I have created 4 UI buttons with on-screen button component with binding W, A, S, D for moving chacater to let mobile players move character but now what should I do to use on-screen stick component button for player movement instead of 4 UI buttons for player movement?
did this but it makes the movement super slow for some reason
if (moveRightAction != null && moveRightAction.IsPressed())
{
Debug.Log("hey lets move right");
var rotation = Quaternion.Euler(0, _camera.rotation.eulerAngles.y, 0);
var direction = Vector3.right * speed * Time.deltaTime;
var rotatedDirection = rotation * direction;
rb = GetComponent<Rigidbody>();
//transform.Translate(rotatedDirection);
rb.linearVelocity = rotatedDirection;
}
``` ^^ what I'm using rn
it's still "moving" but it's like barely even noticable
@naive pawn @queen adder
Don't multiply velocity by deltatime. If it's still slow after removing that, increase the speed value
kk
if using input system unity has pre made on screen controls to work with a vec2 input (I think its a sample)

why is this done again and again?
rb = GetComponent<Rigidbody>();
modifying velocity will break jumping because if we override y vel to be 0 the rb will no longer fall
you can instead get current velocity, modify x,z only and re assign
well how do I do that?
The simplest way in that code is rotatedDirection.y = rb.linearVelocity.y; before assigning
ok so like this works but now it's sliding like there's no friction on the ground (which ? there might not be ?)
I used to many AI to help me code, I feel like a fake dev these days
not sure
Not sure about the friction thing but why are numbers being logged every half a second or so?
it's for a different script, you can safely ignore it
^^ there's also this now which isn't great
you need to add a physics material to the collider i think
Well no i was curious cause logs do slow down the fps quite a bit especially when there are a lot.
which one?
or like wdym
the player capsule collider
the player having high friction helps it not slide when not moving but ofc will require more speed to move
also its often a good idea to greatly reduce how much input changes velocity when not grounded
idk why but changing this also nuked diagonal movement ^^
code rn for context --> https://paste.mod.gg/hzsqajykrhkn/0
I don't see what you mean in the video gimme a sec
Hangon a sec what is this bizarre input
It should be a vector 2
Wasd going into a single vec2 (with a normalizer too)
well how do I do that?
Just curious how come you've decided to put each input direction into it's own input action, there's nothing wrong with it but it seems a bit inefficient to me, you could bind all movement inputs into one action that way you get all inputs as a single vector2 and you use it as you need or am I wrong here
You can have multiple bindings in a single action and have the value type of the action as a vector2
maybe but idk how to actually code it in
also dunno how it fixes this ^^
or this ^^
It's not done in code it's done in your input system action setup where you create the inputs for left right up and down based on wasd, you can have them all in one single action, then that gives you the ability to cast them into a vector2 and you can normalise them easily to fix the diagonal speed issue otherwise you'll have to build a vector2 out of all 4 inputs to normalise them which is messy
Hello 🙂 someone know why i cant disable my Image component ?? public Image Icon; Icon.enabled = false;
What's stopping you?
me ?
Yeah. What's stopping you from doing that?
Is there an error? Have you actually tried it and seen if it works?
I'm coding an enemy that patrols an area by going between waypoints on a Navmesh. I want the enemy to randomly stop moving, rotate 360 degrees, and then continue - in a scanning motion to try and catch the player. The enemy currently just randomly rotates partially while moving straight forwards, causing it to go off the path and act erratically. What's going wrong?
IEnumerator ScanForPlayer()
{
// Stops new coroutine starting until this one ends
isScanning = true;
// Stops agent from moving
agent.isStopped = true;
canMove = false;
// Set agent velocity to zero
rb = GetComponent<Rigidbody>();
rb.velocity = new Vector3(0, 0, 0);
// Failsafe to stop routine after 1000 runs
int failsafe = 0;
// Stops rotation once it reaches 360
while (rotationAngle < 360.5f || failsafe < 1000)
{
failsafe++;
transform.Rotate(Vector3.up * Time.deltaTime * -100);
if (rb.transform.localRotation.y <= 3.6)
{
rb.transform.Rotate(0, 0, 1.0f * Time.deltaTime * 100);
}
else
{
failsafe = 100000;
//canRotate = false;
yield return new WaitForSeconds(2);
canMove = true;
agent.isStopped = false;
isScanning = false;
}
}
}
i didnt tried but VS say i have an error
You have a script named Image or you have imported the wrong namespace. The Image class you are using is not the Unity UI one. Hover over the Image type in the variable declaration and see what class that is
ok
Nothing there changes rotationAngle, and checking localRotation.y is meaningless
it should be something like this:
float rotationAngle = 0;
while (rotationAngle < 360)
{
float rotationAmount = Time.deltaTime * 100;
rotationAngle += rotationAmount;
transform.Rotate(Vector3.up * -rotationAmount);
yield return null;
}
yield return new WaitForSeconds(2);
canMove = true;
agent.isStopped = false;
isScanning = false;
Have you seen how the default actions are configured?
well ya changing this thing vvvv is easy but how do I set up the inputs in the code itself with it?
like what do I replace the stuff in here with? https://paste.mod.gg/pqfbufznieax/0
A tool for sharing your source code with the world!
It say i have the Microsoft and the Unity Image in the same time but i dont know how to have only the unity one
oh no i found how to fix it
ty 🙂
Good now in code you can set your private input action to reference that action and when you need the value, just use inputaction.ReadValue<Vector2>()
I'd recommend reading more on the input system on the documentation as well
He's now spinning uncontrollably the entire time he moves
How are you starting the coroutine?
if (isScanning == false && proxDetect.canBeSeen == true)
{
int scanChance = Random.Range(0, 10);
if (scanChance == 1)
{
StartCoroutine(ScanForPlayer());
}
}
This runs every Update, so if the coroutine is not running (isScanning is off) and the player is within a certain area, it starts the routine 1/10 times
If I coded it correctly
Which I'm now doubting... xD
Yes but if the game runs say at 60 fps then 1/10 times each frame is 6 times per second
Oh
Yo i started learning c# yesterday and managed to code a double or nothing cmd game on visual studio i wanna try unity and take a step forward what are some good beginner projects that could help me learn scripting better?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Or if you want to just dive in and make stuff yourself Flappy Bird is a good one to start with
I don't get it 
show how you set up the action - it seems like it's not configured properly
Looks like you probably have it set up as a Button action
Oh I see - yeah the problem is you set up the bindings wrong
You need to create a new binding and choose "up/left/right/down composite binding" (in older versions maybe also called "Vector2 Composite")
then add all those keys to the composite binding
(and get rid of the bindings you have now)
ok that works but the debug.log just spits these numbers out that change with inputs but like how do I actually know what key is being pressed here?
if i want to increase acceleration but have the same speed, should i just double movement force and drag? i'm trying to make movement during jumps feel smoother in my platformer but i'm not sure how to do it without doing something weird
if you jump and then start moving, it feels really slow and annoying to control
but giving the player a small movement boost when they start moving just feels weird
in the air, i mean
0 would indicate nothing
Or it's failing to update
you can use more drag or you can apply a speed limit in a different way
i'm not sure how to do that in a way that would feel natural
you could also use a higher force for when you start moving than when you are continuously moving
i can't clamp because i want to use momentum for some things
yes I know, the values change whenever each input is pressed, I just dont know what to do with them
that could work
Wdym don't know what to do with them
the most basic way is to just check your velocity and clamp it in FixedUpdate (though this is not a perfect solution because Unity's game loop doesn't apply AddForce until AFTER fixedupdate)
yeah there's all kinds of heuristics you can do. You'll probably need to spend some time tweaking it until it feels right to you
i can't clamp though, i plan on making abilities that will give you momentum instead of fixing your velocity afterwards
thank you for the force doubling idea though
surprised i didn't think of that myself lol
Could have the abilities add to velocity after the clamp
You might be interested in this (free) asset that has a "soft speed limit" feature that might satisfy your needs.
https://assetstore.unity.com/packages/tools/physics/betterphysics-selective-kinematics-244370
@wintry quarry ?
you could probably add something to the string on the line where you call the debug log
generally you're not really interested in "which keys are being pressed" This vector is an input direction you can use in your game now.
E.g. you can more or less plug it into whatever movement system you're using
so it would be easier to know what you're looking at
oh ok ty king
where do I like actually put it though? bcs rn with just this I literally can't go backwards or forwards
Is this 3D? Normally for 3D you'll need to "swizzle" the input vector - i.e. plug the y from the input vector into a z for your actual movement direction
because y is "up", and reight now you're just overwriting the y part with rb.linearVelocity.y
e.g.
Vector2 moveInput = move.ReadValue<Vector2>();
Vector3 moveInput3D = new(moveInput.x, 0, moveInput.y);```
quick question: is there any way to make Rider recognise Unity hlsl symbols like the Light data type? i feel like i might need to add an include path but i'm still not really sure how
You mean in a hlsl file to be used in a Custom Function in Shader Graph? This is only a problem there, since in normal shaders, you would include all the files that have these symbols in them.
It's possible that you can include the relevant files in here, if those include files have guards to ensure they won't be duplicated.
If you're using URP, try adding #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl
Yes, this was for a custom function
unfortunately including this at the top of the file fixes the unrecognized symbols in Rider but it breaks the function in Shader Graph, citing an 'unterminated conditional expression' as well as these errors
I managed to fix the error, but i want to understand it, does anybody have any idea why calling the Handle Input Buffer function in Update would fix the movememnt speed? also is it okay for all this code to be in the player or would i want to seperatr
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.
i've seperate non movement things like grappling
but all these relate to movement
my only theory for why not being able to jump is affecting movement speed is that it's somehow messing up input
i guess if i fixed it it doesn't really matter but I want to know why it's happening
Hi, how i can make my raycast bigger, or autoaim or smt
i mean cuz my shooting feels pretty wacky and i constantly miss the enemy, and i feel like that could go wrong
you´d have to use something else than rc
Spherecast would be a solution , but could cause other problems
how does using charactercontroller compare to a kinematic rigidbody?
for player movement
what kind of problems?
not pricesely enough maybe
pricesely enought?
also what is a spherecast?
in theory would be a kind of very long capscule?
basically yes
i mean, a capsule that would stretch from point A to hit B
oh
well, that seems pretty good
just a very small spherecast
you get a sphere and you send it in a given direction
haha
is optimized, right?
https://docs.unity3d.com/ScriptReference/Physics.CapsuleCast.html then this is even better for you
i thought i would have to do something complex for fix it
so, this IS a capsule that stretches then?
i mean, as spherecast is like a capsule that stretches, this would jsut be
or not? idk im guessing
yes
good
you will have to find out which one works better for you
why make spherecast in the first place?
i mean, spherecast makes a list of spheres into the direction
capscule cast makes a chonky raycast
isn't more usable the chonky raycast?
spherecast draws a sphere and casts it in a certain direction, drawing out a capsule
capsulecast draws a capsule and casts it in a certain direction, drawing out a.. rounded cuboid, i guess

so then capsculecast was never a fat raycast, but a fat and tall racyast
ouch
depends on how it's oriented relative to the cast direction
i just want a fat raycast
that would be a spherecast
can someone explain me why when i fire on this direction, this happens to the cast? (the line is tied to the cast)
maybe its backwards?
i dont think so, is just when the angle is like this, cuz when the angle is more lowered it shoots forward
You need to learn to attempt some debugging before asking questions. A lot of your questions are just "what's wrong?" with a vague image.
sorry...
here's the code
{
Debug.Log("ShootedRifle is even shooting");
rifle_amount--;
// Get the mouse position in world space with correct depth
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.SphereCast(ray, 3, out hit, Mathf.Infinity, demons))
{
Debug.Log("ShootedRifle has Shooted");
Debug.Log("ShootedRifle hit 3D: " + hit.collider.name);
EnemyBase enemy = hit.transform.GetComponent<EnemyBase>();
if (enemy != null)
{
Debug.Log("ShootedRifle's enemy isn't null");
enemy.TakeDamage(5, 1, 3, 3, transform);
}
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, hit.point);
}
else
{
// Ray didn't hit — project forward from the camera or weapon
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, transform.position + ray.direction * 100);
}
}```
weird enought, this issue happens when the spherecast is used
why?
So I'm using a save system, and it's working for all of my variables except the ones set by this dropdown menu. The debugs show, and everything else shows, that the variables themselves aren't the problem. The save system just won't save selectedNumber. Clearly there is something here that I don't know.
{
// this.levelDrop = data.levelDrop;
this.selectedNumber = data.selectedNumber;
}
public void SaveData(GameData data)
{
// data.levelDrop = this.levelDrop;
data.selectedNumber = this.selectedNumber;
}```
is this script attached to the camera, or an object at the same posotion/rotation as the camera?
the script is in player, wich is related to the camera
what is this exactly? And which part isn't working? Saving, or loading? And where is a dropdown menu involved here?
Saving and loading are broken for this value. selectedNumber = dropdown.value + 1
selectedNumber isn't broken though. It just won't save and load.
broken how? What kind of debugging have you done?
you said "the debugs show" but which ones? I don't see any in the code you shared
Basically you've given us very little to work with here
i think i discovered the issue tho i dont know how to exactly fix it
the sphere is detecting the floor
to wich, if i make it dont do it, the ray works as a charm
issue here is
layermasks
I mean, I've debugged selectedNumber, and that's working. The next that displays selected number obviously does that. Saving and loading works in every other script, and I haven't done anything differently. The only different about this script is the dropdown.value.
why did you say this then
i dont know how to exactly fix it
for this
cuz i dont know how to exactly do that
thats for why the exactly was for
they.. don't? they work independantly, you interpret the results together
huh
as shoots, the spherecast must find an enemy at the same time the raycast must find a wall, if any of those both activate, it would count as shoot
Yeah for some reason the whole code didn't paste. Lemme stick it in paste bin.
they don't operate over time
so what do you mean by "at the same time"
when i shot
idk, is just, i want it to work as a spherecast for one layer and work as a raycast for another
holup, what if i do this
{
Debug.Log("ShootedRifle has Shooted");
Debug.Log("ShootedRifle hit 3D: " + hit.collider.name);
EnemyBase enemy = hit.transform.GetComponent<EnemyBase>();
if (enemy != null)
{
Debug.Log("ShootedRifle's enemy isn't null");
enemy.TakeDamage(5, 1, 3, 3, transform);
}
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, hit.point);
}```
you really shouldnt be shooting your ray from the camera in a third person game
oh no, it fires from the player
it decides where to end by the camera
or atleasts thats what i feel like it does
well it depends what the ray is exactly doing. It can make sense to do a raycast from the camera to the game world to determine where the player is clicking, but then a separate raycast from the player to the target for the actual shot
fair enough
a radius of 3 on your spherecast is way too high when your character is only 2 units tall, itll instantly hit the ground upon instantiation
yeah, that seems as the prob, thanks
issue now is, how i can make that a spherecast tries to hit the enemy, but doesnt phase away ignoring the ground layer using a raycast?
spherecast only interacts with enemy layer
raycast interacts with environment layer
yes, oh wait
i did it backwards
cuz i did, if sphrecast doesnt hits enemy then check if raycast hits ground. when it should be, if raycast hits ground then check if enemy should be check
no wait, that wouldnt work
i test it...
@wintry quarry I figured it out. It was my fault.
if you use FixedUpdate nothing to worry about
Nothing to worry about even in update
Not even if you do 100 raycasts every update
Not what FixedUpdate is for
Even if it were a problem for perfomance, FixedUpdate doesn't magically fix that
FixedUpdate is not for physics ok
FixedUpdate is for things where the second derivative of time is important - the rate of change of the rate of change of time. This is mostly used for physics calculations
we are talking about Physics.Raycast right
Yes
Which is not, in any way, dependent on time
And especially not concerned with the rate of change of time
if you say the raycast doesnt belong into the FixedUpdate, why is the official documentation using this method then