#💻┃code-beginner
1 messages · Page 583 of 1
i tried and it doesnt work bc theres no new updates
did you read the page, there is more than 1 step there
yes
follow all of the instructions. simply checking for updates is not sufficient
i did
when i click browse it took me to my files
was visual studio not listed in the dropdown?
thats wrong
if you did it correct it should show in dropdown
it was
then why did you click browse?
bc i already have it at visual studio
then why did you click browse
it's a special unity class
screenshot your External Tools page
alr close VS. click regen Project files button, open script again
i cant click on it
why not
idk
looks clickable from here
dont worry about that rn
just click it and open script from unity
if nothing changes show your View -> Solution Explorer window in VS
now i have a bunch of errors
do i restart visual studio or smth
Hint: The errors are because you made a mistake at the start of the file somewhere most likely
wdym
probably a missing bracket
nvm i found it
check the file from top to bottom , usually where red underline starts its where issue is
thanks
btw you should actually implement that Singleton properly so you don't risk to ever have wrong clone assigned to the instance
https://unity.huh.how/references/singletons#implementation
does anything look wrong with this? it's not chnaging behavior at all, and i read the docs.
Vector3.RotateTowards(
snakeBrain.forward,
_player.position - snakeBrain.position,
Time.deltaTime * 1f,
0.0f
);
snakeBrain.rotation =
Quaternion.LookRotation(
Vector3.forward,
newDirection
);```
Hey everyone, hope you're all alright. I'm trying to get this hitbox to be infront of my character when they change direction. Which I thought was easy and I'm pretty sure it is. In my update function I have
m_meleeHitbox.transform.position = transform.position.ConvertTo<Vector2>() + (1.0f * m_playerDirection)
Which makes sense in my head,
location = 1 unit ahead of player in the players direction
any ideas? cheers
my bullet is spawining inside my player, and sometimes knocking the player, so i tried to fix it by removing the rigidbody, and then adding it after a delay. However i have two problems with this code. no.1, the rigid body, isnt being added to the bullet. And no.2 it isnt moving after the player shoots.
rather than using that weird workaround, just use layer based collision
maybe create a vector 2 variable called offset, and adding it to the position, when he changes directions
why not just make an anchor point with a transform thats parented to front of the player
There was hyperlink to this also: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion.RotateTowards.html
something like this would be more accurate for your case:
float maxTurnAngle = 45f;
Quaternion targetRotation = Quaternion.LookRotation(dir);
Quaternion.RotateTowards(transform.rotation, targetRotation, maxTurnAngle * Time.deltaTime);
Don't forget to apply rotation.
ahh okay thank you, il research that
If I'm understanding what you mean, that's pretty much what Im doing already. The hitbox is a child of the player and the player doesn't rotate when it rotates lol. Its facing the same way but the animations are facing different. So Im getting the player direction from the movement input.
Or I might have just completely misunderstood what you meant
ok so this works but it's not using the correct transform direction it seems.. i want the green arrow to look towards target, not the blue? i'm so consufed by this
Note that you're creating two rigidbodies since you have two AddComponent<T>() after the yield instruction.
Also AddComponent() returns the created component, so you can store it into a variable instead of doing that very inefficient stuff:
Rigidbody2D rb = bullet.AddComponent<Rigidbody2D>();
rb.isKinematic = true;
// ...
ohh because you're only rotating the sprite not the actual root object?
Well Im not even rotating the sprite really. The character sprite is the root object, but instead of rotating it, because it is a top down game I can make the character "rotate" by using the different animations. E.g. I have a walking up, down, left and right animation
ahh okay thank you very much, i was being silly lol
i guess you refer too Z-Axis and Y-Axis by green and blue arrow, if the code works but it aims not the axis you want you should do something to that "dir" before applying rotation
you can refer to 2nd argument of Quaternion.LookRotation
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion.LookRotation.html
whats the issue you're having with the current code?
also it should just be
col.transform.position = transform.position + (dist * playerDir);
just make playerDir a vector3
floats dont change in memory right? only when used in scene?
Floats stay the same in memory until modified.
and do they get invalid offsets after modification
why would it even happen?
What do you mean
Are you talking about general floating point accuracy?
If you try to assign a value to a float and it can't be represented it'll be rounded appropriately
beyond that, nothing happens
ok so if i go too many decimal points then it rounds up
float have it own adress, well 4 adresses since i take 4 bytes, and it stays the same
Floating point format explorer – binary representations of common floating point formats.
you reached the max capacity for 4 bytes then
There's basically a very large basket of numbers that a float can hold. If you try to give it something that's not in that basket, it'll find the closest one instead.
At no point can you ever store anything that's not in that basket in a float
Not sure if this is the right place to post this but my prefab randomly died and I did nothing to cause it. It was working last time I had the project open
Are you using version control? Could possibly be a deleted file/folder associated with it
I am using github, but every other commit has worked fine and I don't think I even changed the prefab last commit
Not sure if you edited the prefab outside unity but it seems that it’s probably a corrupted file. I’d try going back a commit and see if it persists
100% certain I did not edit the prefab outside of unity
can you show meta file of that prefab, and open the prefab itself in notes and show the context
I have a "binary file has changed" message for the entity prefab when looking at my latest uncommitted github changes.
Well whatever happened, unity cannot recognize the prefab with that matching guid. It was either modified or deleted (not sure how) but i’d try reverting and seeing if it fixes
I reeeally don't want to lose these latest uncommitted changes 😅
Just stash them, you can always apply them back
Hmm I'm even getting that 'binary file has changed' with my fonts and im even more certain that those didnt change...
If you tell me how to get that info I will
press on that prefab, right mouse btn, show in explorer then there is .meta file with the name of that prefab
check the guid inside
Uhhh okay I just uncommitted the changes for the prefab specifically in GitHub and it fixed everything
Is this a bug?
I swear I didnt do anything
Could just be human error, you might have done something by mistake not knowing you actually modified it.
Or it was corrupted
or somehow renamed outside unity when it was closed, so new .meta file was generated with new guid
renaming outside unity, when its still open, also cause generating new guid
Now I'm paranoid about malware or some other error because I'd bet my life no input I made changed that file,
Or a bug
Oh well its all fixed ty!
how do I use that pixel per unit size and change the size of the camera without effecting pixel per unit size? I also have Vcam
Maybe adjust your camera size?
I tried to change the ortho size on vcam and it does not work at all
Not sure if that will do much. You need to make sure the camera distance is also modified along with sprite pixel per unit (if needed) to keep the changes consistent with the resolution you are setting it to
here is a snip of what It looks like, all I want to do is make the camera bigger, I like all the pixel settings
So you’re saying you want the camera to be bigger but maintain the same pixel dimensions?
I want to keep the assets pixel per unit number and change the camera size
Not 100% sure but try adjusting the camera’s orthographic size proportionally to the screen’s height while keeping the pixel per unit constant?
I tried but it does not work
Then you’ll probably have better luck in #🎥┃cinemachine
this is the base idea of what I am trying to fix, I was trying with the unity pixel cam but that did not work, do you have any idea of how to fix this?
I haven’t worked with #🎥┃cinemachine which is why you’d have better luck there. Besides, not code related
hey everyone, does anyone else ever deal with script compiling time increasing over the span of working in your project? when i close unity and reopen it, the compile time goes back to almost instant. i don;t want to keep restarting unity to keep my compile time down. how to fix?
can someone help fix the issue where pixels have different sizes in unity
Not much we can go on. Also not code related. Check compression on sprite asset
ill send the settings
Not sure then tbh I don't do 2d much . Try asking in appropriate channel #🔀┃art-asset-workflow or #💻┃unity-talk
ill send it there then
Does anyone know if it's possible to have the new input manager assign different sets of keys (for the same actions) to different player objects
I need to have a game with 2-4 players on the same computer using the keyboard
I understand how bad game design that is, it's for a competition 😭
Yes, the new input system supports local multiplayer
Multiple players on a single input device (one keyboard) is a bit of a special case though, and needs some special handling. There are a few options:
https://discussions.unity.com/t/keyboard-multiplayer/838280
https://discussions.unity.com/t/multiple-players-on-keyboard-new-input-system/754028
https://tomhalligan.substack.com/p/splitting-keyboard-input-in-unity?utm_source=share&utm_medium=android&r=b0ti8&triedRedirect=true
Alr thanks
Would it be worth watching tutorials for traditional local multi-player to try and adapt it
im having trouble attaching my GameController script to my BallLogic script, does anyone know why?
What object has the GameController script on it?
just an empty object called GameController
Drag that in
and BallLogic is on the Ball gameObject
the empty object?
The object that actually has the GameController script on it
Well it's not empty if it has a GameController script on it now is it?
yeah
its not working
same thing happens when i just try to do it with the script
Are either of the objects involved Prefabs?
What exactly are you trying to drag and where exactly are you trying to drag it?
Show full uncropped screenshots
Is the object with the GameController script on it in the hierarchy of the scene, or is it on a Prefab object?
Is the object with the BallLogic script on it in the hierarchy of the scene, or is it on a Prefab object?
I want to access the GameController script from The BallLogic script
Ok so you're trying to drag a reference to a scene object into a prefab
this is not supported
Prefabs cannot reference objects in scenes
its in hierarchy
Both objects?
ball is prefab
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
Prefabs cannot reference objects in scenes. You will need to set the variable after you spawn the object
So should it be a prefab object then?
because I want it to be destroyed then spawned with GameController
Refer to the link above for how to handle this properly
or is there a way for me to get it when it spawns like with GetComponent<>()
ok thank you
Instantiate returns a reference to the object it created. You can just store that reference when you spawn it
but could I get the GameController script into the reference?
You could pass the reference to the object you spawned, using the reference Insantiate returns. But what does the Ball need to reference the GameController for?
GameController sounds like something that should just be a singleton tbh
Here's how to use a singleton: https://unity.huh.how/references/singletons
I have a OnCollisionEnter2D method in Ball logic that destroys the ball when it touches the goal and I want it to also increase a score value in GameController before it is destroyed
Definitely use a singleton
ill check that out
How can I check the distance to the nearest object, not knowing what the object is? Like if myObject needs to be at least 0.2 from anything else in the scene. I have Vector3.Distance but I dont know how to define the second argument.
You would either:
- Have a list of all objects in the scene and iterate over them to find the closest
- Use Physics.OverlapSphere to find all nearby objects, then iterate over that list to find the closest among them. (this requires colliders)
Use a CheckSphere with the radius you want, and if it returns false, there's nothing else within range
Oh if you just want to make sure there aren't any objects yeah you can use CheckSphere
Anyone have an alternative to this that's just as simple?
https://youtu.be/qQLvcS9FxnY?si=Was7iplZSnt7q4fD
Not sure if it's a me problem or what but I cannot get it to work
Very fast tutorial to make an FPS character in Unity in less than a minute!
PasteBin link for code: https://pastebin.com/RXZ1dXgw
GitHub link: https://github.com/dustinmorman/FPSControllerTutorial
Link to my Upcoming Game - Survive the Uprising: https://store.steampowered.com/app/1984690/Survive_the_Uprising/
Link to the Discord - https://dis...
Word of advice - avoid anything that's like "Make a game in ONE MINUTE"
this stuff is clickbait and not very useful
https://www.youtube.com/@AcaciaDeveloper this guy has a good one imo
Looks like CheckSphere works with colliders, what if some of the objects dont have colliders?
In the long run it is going to cost you time, not save time
Then they can't really interact with anything
WIthout colliders you need to either maintain your own spatial acceleration data structures for fast lookups or just keep a list of all the objects and iterate over them all.
Actual tutorials need time to do things correctly. You're not going to find a tiktok that tells you how to make a video game
thank you
the input system is definitely going to be better for this than the old input manager.
have you actually logged what is happening, including the relevant velocity? also you should show the inspector for the rigidbody and aalso make sure that there aren't possibly any colliders that might prevent it from moving vertically
Well, considering the fact that it does jump when I utilize the "Fire" action instead of the "Jump" action I created, I doubt it's something to do with my code
but here's the inspector for the player object
I doubt it's something to do with my code
then why did you post the question in a code channel
ohh you're right my bad
and if it works using the Fire action then check what is different about that action
I did (nothing that I can tell)
oh there's an input system channel 🤦♂️
@teal viper
public void MoveAndRotateToTarget(Vector3 targetPosition)
{
Vector3 direction = targetPosition - transform.position;
if (direction != Vector3.zero)
{
direction.y = 0f;
targetPosition.y = 0f;
Quaternion toRotation = Quaternion.LookRotation(direction, Vector3.up);
// Use Rigidbody.AddTorque for rotation
Vector3 torque = Vector3.Cross(transform.forward, direction.normalized) * rotationSmoothness * rb.mass / Time.deltaTime;
rb.AddTorque(torque);
float distanceToTarget = Vector3.Distance(transform.position, targetPosition);
float deceleratedSpeed = Mathf.Lerp(0f, moveSpeed, Mathf.Clamp01(distanceToTarget / decelerationFactor));
// Use Rigidbody.AddForce for movement
rb.AddForce(transform.forward * deceleratedSpeed * rb.mass / Time.deltaTime);
// Clamp the velocity to ensure it does not exceed the moveSpeed
rb.velocity = Vector3.ClampMagnitude(rb.velocity, moveSpeed);
}
}
in the build exe it moves at different speeds, most likely due to different framerates
Share the whole 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/, https://scriptbin.xyz/
📃 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.
foreach (GameObject element in parent.transform)
{
if (!element.activeInHierarchy)
{
continue;
}
counter += element.GetComponent<Rect>().height;
}
print($">>> {counter}");```
gonna try it
its 1k lines long
ill paste the update function and the movement function
That's why read the bot message.
One issue I see here is multiplying the force you add by delta time. You should not do that.
multiplying?
Dividing. Doesn't matter
what should i do instead
Nothing. Just don't divide it by delta time.
It would also help if you name the variables properly and learn the difference between forces, acceleration, velocity and speed.
If you want to apply an impulse, acceleration or velocity change, you should pass in a second parameter to AddForce. Check the details in the docs.
Hey i was wondering if i could have some help with my code snippet all I'm trying to do is have the camera follow the player with a delay so that the cam doesn't just lock onto the player like just equaling out their transforms would do and I've nearly done it but no matter what i do I cant seen to stop the camera from jittering when the player gets to far away it starts unnoticeable around 1 or 2 units away but gets really noticeable the further away the player is i believe is has something to do with the speed constantly changing but I genuinely have no clue I've been trying to debug for a while now but to no avail any ideas?(sorry for the lack of grammar😅 )
Vector2 direction = playerPrefab.transform.position - transform.position;
//calculates the distance/magnitude between the camera and player
float magnitude = direction.magnitude;
//makes the camera move towards the player
if (magnitude > stopDistance)
{
//normalizes the direction
Vector3 distanceBetweenNormalized = direction.normalized;
//sets the speed
cameraSpeed = magnitude * 1.5f;
//calculates the movement vector
Vector3 moveVector = distanceBetweenNormalized * cameraSpeed * Time.deltaTime;
//moves the camera towards the player
transform.position += moveVector;```
after some testing I thoroughly believe that its the way that im managing the players movement instead of the cameras but im even more lost as to how i can alter that to make it work
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
Vector2 inputVector = new Vector2(horizontalInput, verticalInput);
if (inputVector.magnitude >= 0.9f)
{
inputVector = inputVector.normalized;
}
rb2D.velocity = inputVector * moveSpeed;
}```
This code is generating 50kb of garbage when the Cell.Clone() method is called. Is there a way to bring that down by not calling it?
public class AbstractBoard
{
public InfiniteBoardGenerator boardGenerator;
public Dictionary<Tuple<int, int>, Chunk> loadedChunks;
public int chunkSize;
private int[,] numbersBuffer;
private int[,] minesBuffer;
private Cell[,] cellsBuffer;
public Cell[,] GetChunk(int chunkXPosition, int chunkYPosition)
{
Tuple<int, int> chunk = new(chunkXPosition, chunkYPosition);
if (!loadedChunks.ContainsKey(chunk))
{
ComputeChunk(chunkXPosition, chunkYPosition, ref cellsBuffer);
CellsToChunk(chunkXPosition, chunkYPosition, cellsBuffer);
foreach (Cell cell in cellsBuffer)
{
cell.state = Cell.State.Revealed;
cell.type = Cell.Type.Mine;
}
}
return loadedChunks[chunk].cells;
}
private void ComputeChunk(int chunkXPosition, int chunkYPosition, ref Cell[,] cells)
{
ComputeMinesInChunk(chunkXPosition, chunkYPosition, ref minesBuffer);
ComputeNumbers(minesBuffer, ref numbersBuffer);
for (int i = 0; i < chunkSize; i++)
{
for (int j = 0; j < chunkSize; j++)
{
GetCell(i, j, ref cells[i, j]);
}
}
}
private void CellsToChunk(int chunkXPosition, int chunkYPosition, Cell[,] cells)
{
Tuple<int, int> chunkPosition = new(chunkXPosition, chunkYPosition);
Cell[,] newCells = new Cell[chunkSize, chunkSize];
for (int i = 0; (i < chunkSize); i++)
{
for (int j = 0; (j < chunkSize); j++)
{
newCells[i, j] = cells[i, j].Clone();
}
}
loadedChunks[chunkPosition] = new()
{
cells = newCells,
};
}
}
To not call it directly will copy a reference only and there will be unwanted modifications to the "original" instance
If there's a constant GC there, it means that you're discarding the new objects every frame.
What do you need the cloned cells for and what happens to them later?
I want to have a dictionary that saves chunks of cells so they don't have to be calculated again
So each time the player finds an unexplored chunk, it is calculated and saved into the dictionary
I don't know how to initialize the cells without a new() so I'm always forced to generate garbage that way
Are you sure it's garbage and not just an allocation? For it to be garbage it would need to be allocated/disposed every frame
Does it actually cause a performance issue?
Can you share the profiler data?
It would make a lot of sense to not be called garbage because I do need to create the cells somewhere to save them. I was just wondering if there was a way to store them directly into the dictionary without having to do the intermediate step of cloning the cells one by one (Cell.Clone() returns a new cell with the same values)
Also, I think there's an issue with you using Tuples there. It seems to be a reference type version, so you'll never get them from your dictionary. Use Vector2Int or something instead
Well, if you want the cell objects to be independent from the original objects then you have to clone them.
Not really but I got 10kb and better performance when there was no cloning happening, I just thought it was worth the effort
I actually switched from arrays to tuples because arrays wouldn't work but tuples do
I'd try fixing your dictionary keys first(no tuples) and see if that helps
There's really no reason to use tuples here, since we have vectors
sorry to ignore but how do i start learning coding?
What's the benefit of using vectors here? Would I be able to not use the new keyword? If so, how?
You would still use new, but vectors are value types, so they are not allocated on the heap, and thus don't contribute to GC.
You could probably use a ValueTuple as well, but just don't. Use unity API as much as possible to keep the code consistent.
learn the basics of C# first, then the Unity beginner and intermediate scripting tutorials to understand how Unity uses C# . . .
Nice. Thank you
where do i learn?
any tutorial from YouTube or a blog post. you can check the pinned messages from this channel for the Unity related stuff . . .
ok
Just to make it clear, I don't think that the new tuples are what's allocating most of the GC now. It's just that using them breaks the point of your dictionary as you never find existing chunks in it.
And thus every time you try to get one, you allocate a new chunk
That wasn't an issue actually. Everything works just fine
Add a log in the if block that checks if the dictionary contains the tuple. Does it ever get printed?
Sorry, I mean add an else block and add a log there
oh ok!
Yes, the dict does contain the tuple
That's weird, but ok.
Btw why are you using Tuple<int, int> (reference type) instead of (int, int) which would be value type
Edit: oops, didnt notice dlich pointed that out already
Latter would cut down on allocations
Feel free to correct me if im wrong
Ah, okay. Tuples seem to compare by value even if they are a reference type. Still, you should use a vector or ValueTuple to avoid the allocation of the tuples.
Yeah, its a low hanging fruit
Isn't this the same thing?
Oh, I guess it would be a ValueTuple?
Latter is valuetuple yeah
im making a automatic function to shrink and enlarge dialog based on the elements inside the dialog, just like bootstrap from web development
lets say all the height added up from all elements are 50, then the parent height will be 50 + some offset
however, all these elements u see are controlled by certain vertical/horizontal layout group
when they are under control of the group, i know u cant change the value, but not even getting it???
when u get the value , they return 0, either from rect.height, or sizedelta.y , or getrectheight()
is there any ways to bypass this encryption?
Where are you getting it? Might need to do it at the end of the frame but not sure
private void RefreshDialog()
{
float counter = 0;
foreach (Transform element in parent.GetComponent<Transform>())
{
if (!element.gameObject.activeInHierarchy)
{
continue;
}
counter += element.gameObject.GetComponent<RectTransform>().rect.height;
}
foreach (RectTransform element in coreTransforms)
{
element.GetComponent<RectTransform>().sizeDelta = new Vector2(element.rect.width, counter + 40 + stepParents[steps].GetComponent<RectTransform>().GetRectHeight());
}
GetComponentInChildren<BasicDialogFrame>().RefreshSize(true);
}```
all of them are event driven functions , when u press the button, the next parent is loaded , and this function will be called after next UI parent is set active
https://paste.ofcode.org/iXKchBT9ksWX4JJ5AN2PEZ hello so I have this code which has all the movement needed I have an animation freezing system and the walk animations freeze and after 4 frames they should reset the walk animation but they continue by repeating for 6 to 7 frames and then are switched pls someone explain how to fix it all the animations are of 5 fps and the animator.speed is the problem I think it should be smth like delta time
I tried it but then it slows animator.speed down a lot
I tried setting animatorspeed to 2 but it is unreliable as frames change
my friends shared a way to let me get the value , but it destroys the original layout completely, u cant get the value u want to get with this tho
LayoutRebuilder.ForceRebuildLayoutImmediate(parent.GetComponent<RectTransform>());```
Say in one short sentence, what is the issue
Walk animation's frames are repeating
They are trying to increment the animations frame by frame using the animator... That's the issue.
I told you that the animator is not intended for such use case
The sprite thing doesn't make it better
I saw them manually incrementing spriterenderer frames before
Then there was an issue with your implementation
There's no issue it just isn't possible with the spriterenderer frames
You can see the script if you want https://paste.ofcode.org/8F5y2sKHDeDp4UHvBXZ6gu
Wdym? Of course it's possible.
What's the issue with this code though?
I'm not sure. The non-animator approach might not make it easier. I think the animations don't instantly update when you change direction because public float animationFrameRate = 0.2f;, effectively forcing the frame to linger for 200 milliseconds before it can update to the new direction and the run animation freezes which I don't want
Then change the value. Or don't rely on it at all. Just iterate sprites every frame
If the value is changed the animations are sped up
i found a way to do it now
How??
no its my problem lol
i gonna get the value from here
and its done
Then decide what you want exactly. Do you want the animations frames to last several game frames? Or certain game time? Or be in sync with the game frames? It's not entirely clear what you are trying to achieve.
Wait let me show a video of what I want to achieve
this is what I want to achieve
So basically iterate the animation frames(potentially with some delay) when the input is pressed.
Yeah
Along with run switching to idle and walk running defaultly as well with it
So it's just 2 states: walking and running.
Then you just update the corresponding state every time there is input.
!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/, https://scriptbin.xyz/
📃 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.
once again, im here to ask for help https://paste.mod.gg/orizpmolzzft/0 im trying to make interactions using raycast, to check if its hitting the object i want to interact with
A tool for sharing your source code with the world!
everything works except the true part of HandleInteractions()
the else outputs not interacting, but the true should happen
What "true" part? You mean if (Physics.Raycast...?
yes
This part makes no sense to me cs if (moveDir != Vector3.zero) { moveDir = lastMoveDirection; }
And lastMoveDirection will always be zero, you aren't changing it anywhere
but im changing it when InputVector changes
Show me where
Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
```
Is that lastMoveDirection?
thats moveDir
Yeah I can read
ye
isnt lastMoveDirection dependant on moveDir cuz i add moveDir = lastMoveDir
Of course lol
Hi,
I am following a tutorial on how to make pong in unity as I am just starting out, but I have come across this error even though I am copying the tutorial's code which did not come up with the error.
Error: 'Vector2' is an ambiguous reference between 'UnityEngine.Vector2' and 'System.Numerics.Vector2'
Thank you so much
let me suggest you to NOT copy the code but write it yourself following the code you see from the tutorial.
And for some reason, you import the usage of System.Numerics, which you should not. It just tells you, it cant decide, if you using unity.vector2 or the numerics one, but certainly you want the unity one
Thank you! It worked, from now I will try and just follow along with the code, I am mainly just using the guide to get familiar with what each of the buttons does!
Hello, I'm trying to render stuff using a particle system. For layering I put the particlesystem into depth mode and set the z coordinate of particles to their layer. But it seems like the particle system depth mode doesn't actually sort based on z-coordinate, or not in a conventional manner atleast. How can I specify which particles draw on top of others ones?
Edit: I found a solution, it's not perfect and might introduce problems later on, but for not it works. I will post again if I this solution no longer works in the future
Are you sure this is all done with z-coordinates and you're not using the transparent layering queue as the sort
also #✨┃vfx-and-particles
I use defaultparticle material
I've used it in 3D and it does sort on depth, where as Unity 2D does most with rendering queues and not coordinates
anyway as I said I found a solution so it's not a problem anymore
No so the walk animation iterates through the frames as well as plays continuously when directional keys are held a little longer and the run should play when Z is pressed and when Z is released the idle animation should play on that direction @teal viper
Hi, I have a "small" problem with the car engine.
I did it from the Guide ( https://www.youtube.com/watch?v=gEwNHUDc8uE&list=PL0JXhw1odpJLTRBDdv4ybtYkuD1lEcF-N&index=2 ) and now after starting it doesn't want to go
(as far as I can tell the problem is with the wheels )
In the tutorial we will make a Car controller with smoke particles when slipping, variable steering and camera movement.
The car controller that contains: A car controller script with a car model, that allows the car to accelerate, brake, reverse, drift and countersteer. A camera controller script.
To download the code go to:
https://github.co...
That's what I called it, it should be according to the "Car controller" guide (sorry but I'm a newbie)
Error Codes
post that script please !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/, https://scriptbin.xyz/
📃 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.
always post script and error codes next time btw
it looks like your code is trying to get from the list or array an index which the list doesn't have.
The script is now irrelevant to me.
Wheels.
but it has errors?
code obvs
yea idk what im missing here
i fix it around 7PM
https://youtu.be/4H6-obIxnjg?si=w1kQMlasa4WuPJjy 2:30 he does something with the materials. How would i do this on the newer version of unity
Learn how to create your own classic First Person Shooter in Unity!
Get the assets for this series here: https://www.dropbox.com/s/juihs7yq93x1aon/GPJ_FPS_Assets.zip?dl=0
Don't forget to hit that like button and if you'd like to see more gaming goodness then subscribe for more!
Support the show by pledging at http://www.patreon.com/gamesplu...
This is a code channel, and that's not a code question. #🔀┃art-asset-workflow or #💻┃unity-talk is where you should have asked. "newer" version depends on which render pipeline you're using.. BiRP is the same as in that video. URP is similar, with some names changed.
ok now I know what... Orientation
if (playerSenseRage.Value == true)
{
up.color = _restColor;
right.color = _restColor;
left.color = _restColor;
down.color = _restColor;
center.color = _activeColor;
}
else if (lookDir == Directions.Up)
{
up.color = _activeColor;
right.color = _restColor;
left.color = _restColor;
down.color = _restColor;
center.color = _centerColor;
}
else if (lookDir == Directions.Right)
{
up.color = _restColor;
right.color = _restColor;
left.color = _activeColor;
down.color = _restColor;
center.color = _centerColor;
}
else if (lookDir == Directions.Left)
{
up.color = _restColor;
right.color = _activeColor;
left.color = _restColor;
down.color = _restColor;
center.color = _centerColor;
}
else if (lookDir == Directions.Down)
{
up.color = _restColor;
right.color = _restColor;
left.color = _restColor;
down.color = _activeColor;
center.color = _centerColor;
}
else if (lookDir == Directions.None)
{
up.color = _restColor;
right.color = _restColor;
left.color = _restColor;
down.color = _restColor;
center.color = _centerColor;
}
How can I improve this code?
You could first set them all to their default value (_restColor/_centerColor) and then only change one of them to _activeColor based on lookDir (and playerSenseRage?)
This would be one extra assignment but at least less code repetition
lookDir could be checked in a switch
I would say have a direction mapped to each one so you just compare if the dir matches and set the active/rest colour otherwise
good ideas, thanks guy
switch statements look nicer and vs will usually do it for you if you highlight the statements see what it has to say
doesnt solve this crud though but yes switch statements are good
there's also the pattern match statement which can make it even smaller
!vscode
script option thing? I suggest you go through this first !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
how do u wait for an animation to finish before continuing the function
Check the animation state or wait for its length
how do you check the state
yea im new i dont know much thanks
thats why. It will be easier for you to understand and for us to help, when you know the basics 🙂 And the learn website is really good to go step by step
try google
is this the place to ask about tilemap?
is it related to coding?
rendering tiles in isometric view idk where to ask
probably something within the Artist Tools section
hi guys i am new here
hey guys! just wanna confirm, using GameObject.Find is like, not good at all right? what would be the best way to do it? trying to access a void function from another script and i'm using this:
[SerializeField] GameObject gamemana;
void Start() {
gamemana = GameObject.Find("GameMana");
}
private void OnMouseDown() {
Destroy(gameObject);
GameManager scriptAdd = gamemana.GetComponent<GameManager>();
scriptAdd.UpdateScore(1);
}
it works but just wondering if theres a better way to do this
well you have the field gamemana serialized so why not assign it in the inspector and remove Find()?
Second you can change the type to be GameManager gamemana too to skip the component get.
i did try using that, but my prefabs werent updating, so everytime i started the game they didn't had anything assigned to that field so i just assumed that it was because they were prefabs
If its loaded later at runtime or something id say a single Find isnt too bad but you should avoid finding by a name. Instead FindObjectOfType<GameManager>(); to more reliably get this game manager instance.
The alternative is to make it a singleton
a prefab ASSET can only reference stuff inside itself or other assets.
if placed in a scene then that instance can reference anything in the same scene.
if its something else then can you explain a bit clearer or send some screenshots?
i'm sorry, but i didn't understand that, could you explain with other words?
singleton?
Do you understand the difference between a prefab asset (the thing in the project window) and a prefab instance?
isnt that what i did in GameManager scriptAdd = gamemana.GetComponent<GameManager>(); though? not sure if thats what you meant
[SerializeField]
GameManager gamemana;
the prefab instance is the one that pops up in the game and the prefab asset is the one thats on your assets folder, correct?
oh! so by changing the type i don't have to use GetComponent method?
yea cus its already that.
e.g.
[SerializeField]
AudioSource myAudio;
private void Start()
{
myAudio.Play();
}
@compact stag If the script that wants to reference game manager is Instantiated in play mode then ofc you cannot reference via the inspector (i presume this is what you are doing).
But if its in the scene already then reference it directly like i just demonstrated
Cool then this should work nice and simply
wait, nevermind it is instantiated in playmode
so ill have to change it by code, alright
so if i cant change the reference via the inspector, how should i do it? whats the best way to do that?
If you can reference in scene
[SerializeField]
GameManager gamemana;
private void OnMouseDown()
{
Destroy(gameObject);
if(gamemana != null)
{
gamemana.UpdateScore(1);
}
else Debug.Log("Game manager is missing!", this)
}
Hi new here, make sure to read #📖┃code-of-conduct if you have time
and if i cant should i use FindObjectOfType<GameManager>(); ?
If you cant easily reference in inspector then consider making your game manager a singleton:
https://unity.huh.how/references/singletons
Id try to avoid FindObjectOfType() as say you kept spawning in objects that do this, it could affect performance.
If its 1 find rarely its not too bad (e.g on game load, on level load)
so a singleton is pretty much just a single script with few lines of code (for most cases i assume) ?
its a way to let you easily reference a single instance of a monobehaviour anywhere via a static reference
what you put in it is up to you
alright, ill write a few lines and ill update you soon! thank you either way ❤️
np. that website has lots of good info for how to do stuff
and its way better looking than the actual docs
why tf no dark theme? where are we? 2013? jeez
Just use a browser extension for that
that works but every other website that has dark theme just flashbangs me
question
i made a singleton (or at least i think i did???) and it came out to this
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SocialPlatforms.Impl;
public class SingletonTest : MonoBehaviour
{
[SerializeField] TextMeshProUGUI scoreText;
private int score;
public static SingletonTest instance;
private void Awake() {
if(instance == null) {
instance = this;
}
else {
Debug.Log("Another instance foi found");
Destroy(this);
}
}
public void UpdateScore(int scoreToAdd) {
score += scoreToAdd;
scoreText.text = "Score: " + score;
}
}
can i apply this code to any game object or...? what should i do? because i do need to reference the text mesh somewhere
elsewhere you use SingletonTest.instance.UpdateScore(1)
and then instead of putting my variables in this code i put it in the other code?
er can you be more specific?
i was about to say lol too vague
using this singleton pattern is to get a reference to a script instance easily without find/inspector ref
so, i was thinking of putting it in my "enemy" script, as when you click on an object it disappears and you should get a point, its a recreation of the game fruit ninja
then in the enemy script. use SingletonTest.instance.UpdateScore(1) to update score.
Perhaps you should read up on c# basics if this is confusing
it isnt! i'm just wondering where i'd put the [SerializeField] TextMeshProUGUI scoreText; private int score;
should i put it in the singleton script or in the enemy script?
in your singleton script ofc
your singleton manager class is managing the ui text and score value so it goes there.
enemies get created/destroyed a lot so should just tell the manager to update score when needed.
right, so since i have a serialized field that takes my scoreText i'd have to put this singleton script somewhere, correct?
so i can reference my text mesh through the inspector
the enemy doesn't (shouldn't) need to know about the score text or the score . . .
Yea, have 1 instance of the manager in the scene as otherwise it wont exist
@compact stag when the enemy dies, send an event (notification). have a score manager or your singleton listen to this event and update the score accordingly . . .
Scene loads -> manager sets instance static ref -> spawn enemy -> enemy dies -> tells manager to increase score.
so i'm assuming i can put it anywhere or like, do i have to put it in somewhere specific? i dont think it matters right?
i know that! i'm just wondering where i apply this script so i can reference my text mesh because idk if it matters
what game object it goes on makes no difference. as long as its in the same scene and it isnt destroyed too early.
gotcha, thank you! thats what i wanted to know
ill put it in my game manager as it doesnt get destroyed
where? it's just a script. it has to be on a GameObject; that's all that matters . . .
Some people however like to do DontDestroyOnLoad() on their singleton so its safe from being destroyed on scene changes
thats fair, how would i apply it on my code? just use that method in the singleton script?
since its a simple recreation game to learn stuff i won't be using that but its always good to know
ill take a look at it as soon as im finished here, but another question popped up in my head, sorry for the billion questions
but why do we use serialized field?
to view the variable from the inspector . . .
yes, but why not use public?
you probably know that public int myInt also works to have a var in the inspector right?
this allows us to change/edit the fields' values while keeping it private (inaccessible from other classes) . . .
correct!
i see! but why do we use that and not protected? i'd assume that it does the same thing, correct?
well protected lets sub classes also access it and ofc you can use that if you want
usually wise to start with the least access and change as needed
protected ensures we can access the field from a derived class. if that is your intent, then use it instead . . .
protected everything
a private field cannot be accessed from a derived class, only the enclosing class (it was created in) . . .
the cooler private
how do i make it so when i look down my player doesnt do this and ill send the link to the script in a bit
alright! thank you guys, much love! i'll let the other beginners take the chat
good luck! 🫡 🫵
a powerful website for storing and sharing text and code snippets. completely free and open source.
Nothing here is rotating your character
ye where be it
you mentioned, "look down," but your code (and class name) only indicate you're moving the player, not looking or rotating it . . .
oh i forgot the turning script
wouldn't that be the only one to send?
a powerful website for storing and sharing text and code snippets. completely free and open source.
instead of rotating the whole body, why not rotate the main camera?
how do i do that
put the script on your camera instead of on your player
but then the player doesnt rotate at all i think
You can do Y rotation for the body and X rotation for the camera
well why do you need the player to rotate at all?
yeah exactly that
i still dont understand how i can do that
If you understood your own code then you'd know how to do it
You are already doing it, just need to split it up
they are saying your script makes the body move. instead, make the camera move . . .
also, just use cinemachine. it'll solve all your problems and has a bunch of tutorials for different types of camera views . . .
how did you even write the code so far then ?
tutorial
We all know where that code came from
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.
Which one?
here was my approach
wait let me check
probably copy pasted from unity learn tutorial
didnt it explain which part does what?
nope
i didnt do the unity tutorial tho
so which one
#unity #fps #tutorial
In this series, we are going to create a first-person shooter game in unity.
We will learn how to develop all the different features that are common in FPS games.
From basic movement to shooting modes, impact effects, animating the weapon models, ammo management, enemy ai, and more.
Full FPS Playlist:
https://www.youtube...
this one
oh wow even crappy video put Time.deltaTime on mouse Input
I was almost sure that it's from ChatGPT (though the comments weren't exactly gpt like)
This is what ChatGPT gives
It always does thet deltatime mistake
brackys!!!!!!
goddam brackys mistake has influenced GPT too ? rip
Because it copies of the internet.
so how do i fix the thing i was talking abt
why is the deltatime not needed?
mouse input already independent from framarate
And in this case the tutorial maker might have used ChatGPT so it's recycled twice
Look how similiar it is
my brother who makes unity games gave me the link
This is why I don’t recommend using AI for programming
my cousin works at nintendo
get a reference to the main camera and do this
the returned axis is already the position since last frame, so its already framarate independent
See, the cool thing about Godot is AI is terrible for it and is way behind. So you're forced to actually give some legitimate code to work out ;p
Get a refrence?
Maybe you should consider doing the learning tutorials
mouse input is already a delta (a change in position). it is not dependent on frame rate . . .
Choose the best way to reference other variables.
You can start here tho
https://learn.unity.com/pathways
you're better off
Does anyone know how to save a blendtree and connect it to a player? I have my blendtree setup, but its not connected to my player, my player has a diffrent animator component and i dont know how to change it. this pic might be a little confusing, but the inspector tab on the right is my setup blendtree, and the animator tab on the left is the one my player is connected to
you have to create parameters you change through code
I have paramters, its kinda confusing idk how i messed this up so bad
MouseX and MouseY have to be created
The paramaters are correct and working on my inspector tab
i can move the red circle around and it will work properly
also
where? they're not in the parameter
public class PlayerController : MonoBehaviour
{
private Rigidbody2D myRB;
private Animator myAnim;
[SerializeField]
private float speed;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
myRB = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
myRB.linearVelocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * speed * Time.deltaTime;
myAnim.SetFloat("MoveX", myRB.linearVelocityX);
myAnim.SetFloat("MoveY", myRB.linearVelocityY);
}
}
this is a diffrent component
im trying to figure out how to connect my other blendtree to my player
why are you showing different one then
the process is the same, make the paramaters and control them
im explaining the poorly i think 😭
probably
ok so
im following this tuthttps://www.youtube.com/watch?v=gKauseRHFRg&list=PLLtCXwcEVtulmgxqM_cA8hjIWkSNMWuie&index=4
Check out my latest video! : "Topdown 2D RPG In Unity - 22 Player Stats"
https://www.youtube.com/watch?v=9eh41WPlD_g --~--
In this video, we will be creating some walk animations for our player, and hooking up those animations using the animator and a C# script.
I setup the blendtree correctly, but it wasnt linked to my player
also you shouldnt move rigidbody in Update but Fixed Update instead, and adding Time.deltaTime on velocity is hella wrong
my player has a diffrent animator component linked
Ive never programmed in C# before, im just following a tutorial trying to learn basics of unity
the tutorial is teaching you wrong
thats why we normally start with the learn site from unity
https://paste.ofcode.org/jBtb4xxJmTPrqaXzw649hZ this works but another problem is that after running when the directional key is released and then Z key is released the walk animation is played instead of idle pls somebody help
its 5years old lmao
regardless of age, its wrong
you can use whatever tutorial if you're aware of the mistakes to correct, which are hard to do when you're new lol
whats so bad about this tho?
Man why are these people so confident to make these tutorials
what they're saying is, you should receive the input in Update, not FixedUpdate to avoid missed frames, and when assigning velocity, deltaTime is not needed . . .
No one gets movement physics or mouse look or other basic stuff right
also
what i was trying to ask is how do i connect my blendtree to player component
I have the animator option
but it just makes a whole new blendtree
am i slow
i'm surprised at how many tutorial links we've received are incorrect . . .
seriously took me ages to drop the few ones i have myself because I always triple check and delete anything that isn't correct or proper.. but thats just me lol
ok i get the tutorial is wrong but i think you guys dont get what im asking 😭
but that explain why mine are stuck at 5k views xD
ill use a dif tutorial after this part
What do you mean? Blend trees are part of your animator - or the animatorcontroller really
They are just another state
did you add an Animator component on the player GameObject?
if you already have examples of the other blend tree, copy it no ? tbh not sure 100% what you are asking
wdym "connect" like a reference you mean ?
regardless of which mouse key is pressed
it always does animation up
howevere
my blendtree is correct
Then there's this guy who gets <1000 views
But he worked on Bioshock Infinite and Total War and makes decent AI tutorials and other intermediate stuff
look
honestly, if you have a blendtree it should already be a part of your Animator . . .
you have the transition to walkup tho is that the blend tree?
yes, its connecting to the wrong one
how do i change which one its connecting too?
my player animator component is using the wrong blendtree
modify the coordinates
ok i think im js slow ngl
wow yeah hidden gems like these. Love it 🔥
in the inspector
or you talking about the state ?
thats what the guy said to do in the tut is make a window in inspector💀
im gonna watch a new tut after this
this one is very painful
follow the structured courses on unity that actually build you up to all the components
which one is the blend teee tho?
WalkUp and WalkDown are pretty confusing labels
ok? I get that but you didnt make the parameters that control those?
you should watch this one https://youtube.com/playlist?list=PLLf84Zj7U26kfPQ00JVI2nIoozuPkykDX&si=dv5gC9e44INYiKqY
I wish i could send a screen recording
ok
thank you
I was trying to find a tutorial
np
so like
i just fucked it all up tbh
where is MouseX and MouseY
man you gotta start with like Flappy Bird or something, an RPG is gonna be too complex as a first project
This is not exactly a coding question but since it's my first time using unity in 2 years and I recently switched to linux, is this how the editor is supposed to look or am I having rendering issues?
it is the global light
those are parameters you wrote but they are not the ones you created
Where shuold I ask something aubout a bug
here
why did you post in coding channel if its not a coding question ?
Alright, thanks. It was just switching between red and blue as I move, so I thought it's not rendering properly.
Because I could not find a channel for basic questions, lol, sorry.
ok im just gonna restart the blendtree
no I think its probably fine or you can test it by switching to game window or deleting the light
#💻┃unity-talk look in the #🔎┃find-a-channel next time and read the labels
or perhaps learn how the tool you're using actually works before using it?
if you're gonna use animator, then you need to learn animator first
not Learn as you do something else
BlendTree expects you to have the parameters ready to go for the dropdown, You can type them in but it just resets because it expects the one from Parameter window in animator
oh btw I have a quick question https://paste.ofcode.org/jBtb4xxJmTPrqaXzw649hZ this works but another problem is that after running when the directional key is released and then Z key is released the walk animation is played instead of idle can someone help pls
is there a reason to manually swapping frames instead of just using animtion clips
yeah it is easier and I can do it with less booleans because originally I had many many problems with animators trust me it is very much rage inducing
this is pretty old too is it still going to be good code?
so i dont have to deal with the outdated code like in the other yt vid
yeah I made my first game with it
the code in the video wasnt outdated, it was just poor
it is a basic tutorial for newbies
much better to learn here
https://learn.unity.com/pathways
yeah its a good source
at least this treats it like school material with assignments and such
the other videos on YT you're just copying and pasting , not learning
ok thank you for the help guys
no problem
and also sprites are just easier to use than animators
Well this is your current logic for setting the idle animation:```cs
else if (Input.GetKey(KeyCode.Z) && !Input.anyKeyDown && !Input.anyKey)
{
spriteRenderer.sprite = GetIdleSprite();
}```
Why are you checking if Z is being pressed here
Because then otherwise the idle frames would start to play instead of walk animation instantiating frame by frame
This whole thing is pretty confusing
You posted a video of what you want earlier, it looked like the "idle" animation was just a single frame from the walk animation
is there a good tutorial for learning the basics for the unity UI
@buoyant finch Describe clearly:
When do you want Run anim
When do you want Walk anim
When do you want Idle anim
idk why but i cant even snap windows into diffrent parts of the layout, so everything is just a floating window and its annoying asf
#📲┃ui-ux check pins
also not a code question
when z is pressed and a directional key is used the run animation should be played and when the z key is released it should switch to idle animations.The walk animation should be iterated frame by frame with subsequent key presses and when held for some time switches to a consistent smooth walk cycle
So when you stop running you want to go to idle
But when you stop walking you don't want to go to idle?
yes
as the walk animation is iterated frame by frame
I have achieved that all but when I release the directional keys and then when I release Z sometimes walk animation is played instead of idle
If you run and then release Z before releasing directional keys then yeah of course it will go to walk
Hey! I need help with the rotation of the player with the camera.
I have a character controller and the player can move left-right and forward-backward. And have set up a freelook cinemachine camera.
What I want to create is that-
The player rotates with the rotation of the camera and also goes forward in that direction. I don't want the player to be rotated with movement keys (wsad)
No I release Z after releasing the directional keys @verbal dome
The player rotates with the rotation of the camera
For this, instead of using FreeLook you should write your own code that rotates the player and use a camera setup that follows the player's rotation
and also goes forward in that direction
Rotate your input movement vector according to the player's rotation. Simple:
inputVector = player.transform.rotation * inputVector;```
But FreeLook is intended to have decoupled player and camera rotation, so it's not what you want
So I'm still working on this camera shake but
i'm confused, when i first spawn in, the camera is already shaking and i need to dash to reset it
using UnityEngine;
using Unity.Cinemachine;
public class CinemachineShake : MonoBehaviour
{
public static CinemachineShake Instance { get; private set; }
CinemachineCamera cinemachineCamera;
private float intensity;
private float time;
private float shakeTimer;
void Start()
{
Instance = this;
cinemachineCamera = GetComponent<CinemachineCamera>();
}
public void ShakeCamera(float intensity, float time)
{
CinemachineBasicMultiChannelPerlin cinemachineBasicMultiChannelPerlin = cinemachineCamera.GetCinemachineComponent(CinemachineCore.Stage.Noise) as CinemachineBasicMultiChannelPerlin;
cinemachineBasicMultiChannelPerlin.AmplitudeGain = intensity;
shakeTimer = time;
this.intensity = intensity;
this.time = time;
}
// Update is called once per frame
void Update()
{
if (shakeTimer > 0)
{
shakeTimer -= Time.deltaTime;
if (shakeTimer <= 0f)
{
// Timer is done
CinemachineBasicMultiChannelPerlin cinemachineBasicMultiChannelPerlin = cinemachineCamera.GetCinemachineComponent(CinemachineCore.Stage.Noise) as CinemachineBasicMultiChannelPerlin;
cinemachineBasicMultiChannelPerlin.AmplitudeGain = Mathf.Lerp(intensity, 0f, 1 - (shakeTimer / time));
}
}
}
}
there is some easy simplification here that I'm just not remembering could someone point me in the right direction
if (...) {
}
else {
}```
or... really I guess I would just get rid of the second if entirely here
yeah ig its kind of useless
There's no circumstance in which it should be null by then right?
yeah
And if it is, we would want an error message
rn there will be no error if it is, which may be confusing
i was more referring to the inputActions bit tho, i really dont like calling it by name especially since its a group project
You could just directly reference it instead of using Resources.Load
could you elaborate? as in via inspector or?
yes
ah okay ill try that
And if you mean the .FindActionMap and FindAction stuff - you could use the generated C# class instead
oh yeah i forgot about the generated class
there's a slight simplification you can do with the current method though:
inputActionsAsset["Command/MoveTo"].performed += ...```
i did some stuff with the input system a while back but im just jumping into it again on a new project and its like my mind is blank lol
Zenject simply doesn't work, I tried through various methods, tried to fix it with the gpt chat but nothing helped, does anyone have a solution?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Tags dont exist I dont know what you're talking about
Tags are (almost) useless; for everything they do, a better option exists. layers are for performance critical filtering. Tags are like an unlimited number of layers. The name ‘tag’ is misleading since each object can only have one tag.
Interfaces will always be the better identifier
Tags have no use case outside of your own code. Nothing internal will actually use them.
Layers are another case, there are a few layers that Unity provides that have some built in functionality, such as the IgnoreRaycasts layer which, as the name suggests, ignores raycasts, or the UI layer, which is what a canvas defaults to displaying and ignores everything else.
You can add functionality to either of them in your code by checking tags with CompareTag, or by using LayerMasks for things like physics queries
They are also largely without relevant builtin functionality though.
Yes, any layer you define will by default have no functionality tied to it
It's just that there are some layers that come with some baggage built in
You put everything on default until you have a functional reason not to.
The ultimate problem with tags is that you can only have one per object
They are just less performant layers
otherwise I would probably use them if I felt lazy enough not to include my own bitwise enum indentifiers
Unless you've specifically coded some physics queries to look for specifically Interactable or Ground, they're the same
I would encourage anyone to not use layers for identification, only for performance oriented filtering
This OverlapSphere will only detect colliders on objects with the "Interactable" layer
What is the specific problem? Is the issue that the OverlapSphere is detecting things that don't have the layer "Interactable", or that there are "Interactable" objects the overlap sphere isn't picking up?
Well, have you told it anywhere not to do that?
Okay, and what does GroundLayers do?
In your screenshot you've also got "Exclude Layers"
What does that "checkIfGrounded" function do, exactly?
Since every new gameobject defaults to that I would just make a dedicated layer
There's also a matrix where you can set the layer interactions for physics in the settings instead of setting it independently per body
I believe if you set the exclude layers to "Everything" then specifically un check the one layer, it'll automatically mark new layers as excluded as you make them
if you want to go about it the opposite way and just use "Include Layers" then turn off all physics interactions in the matrix and use that property instead
There's actually always 32 layers, even if you haven't made them yet. Setting it to everything will mark those even if you can't see them
https://paste.myst.rs/9m1fn6y7
Problem is here ^
a powerful website for storing and sharing text and code snippets. completely free and open source.
Ping me pls if you answer
Half an hour to copy it there 
{
CellClass cellClass = new CellClass();
return cellClass;
};
itemDeck.bindItem = (element, i) =>
{
element.dataSource = inventorySettings.Types[i];
ListView listView = element.Q<ListView>("EListView");
if (inventorySettings.Types[i] == null)
{
inventorySettings.Types[i] = new ObjectData();
}
listView.itemsSource = inventorySettings.Types[i].paths;
listView.makeItem = () =>
{
return new FloatField();
};
};
why floatfield not being add in ElistView (on ui )?
Hello, what's the easiest way to get a LateFixedUpdate going?
If you use an inject ID with a method you should attach the attribute to the parameter, not the method. See example https://github.com/modesttree/Zenject#identifiers
You can use FixedUpdate on a script that has a high execution order so it executes late
That is a conceptually flawed idea, it would make more sense to implement custom sequencing of your fixed update methods
Why would that be the case?
sometimes you wanna make sure some positions are set before you do other stuff like custom collision
Just wait for the next fixed update
that seems like a more flawed idea, why do that?
it's unneccessary delay
Easiest would be to use UniTask, it has timing hooks for that kind of thing
anyway I just thought of a way to do the thing I need to do, positions are batched already so some sort of manager that calls position updates, then collision checks will work
I always prefer managing stuff like this manually yeah
in 2d, how can i create a freecam system like in the editor, but using scripts and inside the play mode?
thx for help 
But after restart it worked
The script is included as part of any render pipeline, called free camera I believe
where can i find it?
Like you find any component
is there one for 2d?
it would be the same, trivial to adjust in any case
Hey, I somehow managed to do this thing without losing the free look cam, I deleted my move script and used a 2D blend tree with root motion enabled. So, the character is moving according to the input and also not rotating when I press "a" or "d"
And then just assigned the camera's eulerAngles.y to transform.rotation
Well I needed the cinemachine camera for applying some shakes later.
It's working but what do you think I should have done? I mean what's the better way? Creating a new script for camera and player?
Still use Cinemachine, just don't use FreeLook
Oh ok
Which one to use then?
For this 3rd person character controller?
ive made 2d games before but im working on my first 3d project and i honestly have no idea what im doing haha. i made a model for a character and am just trying to do basic movement but when i use controls on him, his body splits into two separate parts going different speeds. i made this script for him but i cant figure out why he splits like this. is this a model issue? or am i doing something wrong in the code?
{
public float speed = 5f; // Movement speed
void Update()
{
float moveX = 0f;
float moveZ = 0f;
if (Input.GetKey(KeyCode.W)) moveZ += 1f;
if (Input.GetKey(KeyCode.S)) moveZ -= 1f;
if (Input.GetKey(KeyCode.A)) moveX -= 1f;
if (Input.GetKey(KeyCode.D)) moveX += 1f;
Vector3 move = new Vector3(moveX, 0f, moveZ);
if (move.magnitude > 1f)
{
move.Normalize(); // Ensures diagonal movement speed is the same as straight movement
}
transform.Translate(move * speed * Time.deltaTime, Space.World);
}
}```
sorry if i interrupted
discord cant embed mkv files
my bad 😭 i had to clean install windows and it wiped my settings
no, you generally want to record in mkv and then remux the recording into an mp3
and for good reason. mkv files can be recovered should anything happen mid recording (crashes, power outage, bluescreen...)
thus is why the remux recordings option is even there
we can, it just doesnt embed
lemme rerecord it rq thank you
but for the sake of posting a recording to discord, mp4 is perfectly fine
yes but the remux button is a single click and safer
its cumbersome to change it back and forth in the settings. im sure this person is planning to use OBS in the future too
isnt that only a discord nitro feature?

oh thats weird, downloading that .mkv file saved it as .mp4
how odd
right? nothing in my script should impact the rate of individual meshes i would think but...
it's a feature
you probably just placed the movement script onto multiple objects
does anyone know how to cut off the particle emitter
i want it to stop where my cone ends
oh mb
that'd do it thx
can i exclude 0 values from json
Remember JSON is just a data format
Members that have the value 0? Or all members that have default value?
you can do whatever you like
If you're talking about "In Newtonsoft JSON", then yes, using the Ignore mode for DefaultValueHandling:
https://www.newtonsoft.com/json/help/html/t_newtonsoft_json_defaultvaluehandling.htm
ex:
string ignored = JsonConvert.SerializeObject(invoice,
Formatting.Indented,
new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });```
yeah i wanted do something like exclude default values
public class ParticleEmission : MonoBehaviour
{
[SerializeField] ParticleSystem dustParticles;
private Rigidbody2D parentRb; // gets the rigidbody of the parent aka the player
private CapsuleCollider2D capsuleCollider2D;
void Start()
{
parentRb = transform.parent.GetComponent<Rigidbody2D>();
capsuleCollider2D = transform.parent.GetComponent<CapsuleCollider2D>();
}
void Update()
{
bool isTouchingEmissionLayers = capsuleCollider2D.IsTouchingLayers(LayerMask.GetMask(ScStrings.groundLayer)) || capsuleCollider2D.IsTouchingLayers(LayerMask.GetMask(ScStrings.railLayer));
Debug.Log(isTouchingEmissionLayers);
Debug.Log(Mathf.Abs(parentRb.linearVelocityX) > 1);
if (Mathf.Abs(parentRb.linearVelocityX) > 1 && isTouchingEmissionLayers)
{
dustParticles.Play();
}
else
{
dustParticles.Stop();
}
}
}
not sure why the particle effects aren't playing both of the Debug.Log's are outputting true as expected
Came up with an idea for creating a passenger system for a taxi game, let me know if it's feasible/needs adjustments: player gets to passenger, script for player to interact with passenger, adds +1 to passenger count (thinking I might add a limit to this so player can only pick up 1 passenger at a time), this also destroys the game object/
Passenger.
Also an area where player drops off passengers, basically checks passenger count and -1 to it

Just wondering what stuff I'd use for the code, I'm very new to coding and only know a few things. I know I'd use variable for the passenger count; could I use an if statement and a trigger to do the picking up passengers thing?
Hey, is there a way to use SceneManager.LoadScene but without using the scene list in the build settings?
I have a project with a lot of them and I would like to do something like passing them in parameter of my script or something, if it's possible
Are all the passengers identical?
yes. but asking if its going to work or not completely depends on what you do. we cant predict that. better off talking to a rubber duck at that point lol
you're probably looking for SceneReference
You mean, you dont want to add them there or what exactly?
They still need to be in the build list no matter what
Yeah I would rather avoid adding them there
I'm making a game with lot of minigames and each minigame is a scene added additively, but linking everything in the scene list is a bit annoying
I'm thinking of making them all simple shapes (probs just capsules), I suck at art and don't have enough time.
AssetBundle or Addressables?
for something more simple u could use a list or dictionary
Make an editor script like this: https://discussions.unity.com/t/how-to-add-scenes-in-build-with-script-with-editorbuildsettings-scenes/463788
how so?
!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/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
That looks interesting I'll hhave a look thanks
i can see it getting annoying when you've got hundreds of scenes or something. since you can barely organise them in the scene list. thats the only real case i can think of though
Yup that's why, I'm also trying to make a system so people can easily add their own minigame without changing code but I don't want them to forget adding the scene
you can use addressables to load them in a performant async way
I guess that can be well combined with the github link above, to get these addresses?
wait players? or like, other devs
I'm mainly working with artists that have Unity knowledge but few dev knowledge
So I'm trying to make tools so it can be as simple as I can for them
ah, ok, "people" was kinda vague there and it kinda sounded like you meant players lol
Yeah my bad :p
Id build a script that adds the scene to a global list with some simple GUI button.
I'm thinking maybe use the GitHub above so they can reference the current scene of the minigame inside a scriptable object where other metadata about the minigame would be, and then doing that yeah :)
If its for artists, I would really make them stick to the inspector best case. So you have your scene config script or whatever, and as soon as this script is added to a scene, it will on editor add itself to the list of some SO you created and inside the inspector show the objects properties, your artists should assign.
That sounds like a great idea too :) I'm reading a bit of everything but I might go with that yeah, thanks a lot
Oh, thnx
feels strange lol
nvm figured it out
thats a cool idea
Is there a way to require a serialized Scriptable object field (exposed through the inspect) to implement a certain interface when assigning it in the inspector?
maybe [SerializeReference] public ISomeInterface ? You might not even need [SerializeReference] since an SO is already a reference? what have you tried?
when my player goes through portal with all of the coins and a key, nothing happens
Hey, I have added a script template following an Unity guide:
https://cdn.bfldr.com/S5BC9Y64/at/5v473vn8kz7p85275gw8vnph/2022_WritingCleanerCodeThatScales_EBook-v6-Final.pdf?#page=1
Page 54, restarted editor and I still don't see the script in the context menu.
Any ideas what to do?
Seems like I Have 2 folders, one for Unity and another for Unity 2022
But neither of them works with the above
2 Folders?
in C:\Program Files
following the above guide
either way, both folders give me same result
open task manager to check if you put it in the correct editor installation? (it can show the path of a process)
do I really have to set templates for each specific unity version?
You could just use unity hub
Based on what I Found my installations are in:
C:\Program Files\Unity\Hub\Editor\6000.0.24f1\Editor\Data\Resources
But the guide says:
Windows:.C:\Program.Files\Unity\Editor\Data\Resources\ScriptTemplates
Is the guide outdated?
tbh I have resource folder in all of these folders
I highly suggest you go through !learn instead of some random tutorial
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
can someone help me with this
Randomly chosen I mean. You seem not to be familiar with the basics yet, so it would be more useful to go through the beginning tutorials before an ebook on a specific sub topic
I guess, you are moving the player with ignoring physics by using transform.position
idk what that means
I just want to make a script template, what does Unity Learn do to help with that specific question?
https://learn.unity.com/search?k=["q%3Ascript template"]
Nothing about script templates in Unity Learn
It means, if you move your player with transform.position, the physics checks are ignored. How are you omving your player?
i think i found it
So from what I see, I guess you need to paste your templates for each version
Thats why I asked here, I am asking someone that knows how to do it.
idk what to do tho
I mean, the guide you have is obvious. Place your file in the template folder of the version you want to use it with
thats just resetting the player to start position. Seems like you should go to the basic tutorials, because you cant find your spot in the code where you move your player.
The guide doesnt say that, it points to this folder:
Windows:.C:\Program.Files\Unity\Editor\Data\Resources\ScriptTemplates
Which is not version specific, version specific folders are elsewhere, I would suspect that it would work for all versions otherwise why is it even here?
Something has changed between Unity\Hub and Unity\Editor at some point I guess
Unfortunately I am on mac, so I have an app bundle for each version. In your hub resource sfolder, is there a scripttemplates folder?
Looks fine so far. You should Debug.Log all your if statements, to check if they are met
script templates folder is everywhere, both in hub and editor folders.
Hub has version specific and editor is for everything I guess, cant tell as it doesnt have a version
it is 5 years old tho, so maybe its no longer used 😄
I would remove all not hub related installations and go along with hub 😄
Unlucky, I'd have to set templates manually for each version.
There is a way to automate it tho, but by trying to "save" time I will waste more of it automating the process than simply not having a template lol
Guess it's fine for larger teams, but not for me 😄
why for each version? If its for one project, you can even place it in the projects folder
now i have this error
Yeah I know that, but per project is even worse 😄
from what code?
my playercontroller
So you wanted a one for all versions template folder. Symlink it to one folder on your computer 😄
also the player isnt colliding with the portal at all
the link doesnt work
they pasted it wrong:
https://unity.huh.how/physics-messages/collision-messages-2d
my portals a trigger
and its under the same oncollisionenter as the coins so i know thats not the problem
Is your IDE configured? That looks like a lack of highlighting that would indicate to me it isn't.
You should have errors underlined in red and advanced autocomplete if it's working correctly
how do i configure my ide
!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
thanks
when i click browse it takes me to my files
If you're using VS2022 then that step looks already valid?
If you're not, then you'll need to browse to your IDE's executable
@astral falcon u still online?
How do I get my code to check if a variable is equal to a specific number? Asking cuz I know that there's a difference between == and =, so wondered which one to use
Oh, thnx
you could make worldspace canvases and place them in the world if you want it to be UI, or you can always just make an object with a textmesh and a SpriteRenderer and put it in the world that way
I don't know what your game is, but the simplest thing is probably to have your 'items' each include a worldspace canvas as part of them
the real solution is to detect the object via say a raycast and in you UI reveal some UI element and you move it to follow the world position
you can convert from world to pixel space via camera.
ofc you will keep updating the ui objects position to follow the object until you decide to hide it.
Yes overlay mode.
its gonna take some tuning...
lots of tuning.. u need to have good offsets.. u need to have it face the camera..
theres a few other things i uneed to do to
You could have the "X to pickup" thing in world but id advise against unless you desire it to appear like its really in 3d space.
Yea ideally your system that detects things you can pickup can somehow report an item is able to be grabbed so your UI can show this info and follow until this state changes.
That to me is the "jank" solution because ofc it can be hidden or stick into stuff accidently soo easily.
there is a component to make something look at something
if you wanna do the jank way so be it 🤷♂️
i did warn you 😆
That might be a reasonable solution, havent worked with symlink but it shouldn't be too difficult I guess
with that way you can use world to screen point and set the .position of your ui element and it will work
line count isnt really a good way to judge code
yep, in practice it probably doesn't matter for most things, but if that solution makes sense to you then it's probably cleaner
Is anyone able to help me out with a small problem that I ran into?
The world canvas approach is perfectly fine. Neither is more performant than the other. If you care about performance, don’t use canvases at all.
well you're still going to have to process all of those things to figure out which ones to display in your overlay canvas
Tutorials are never doing the things that are right for your project.
They do what’s right for a tutorial.
And one truth about tutorials is that real solutions would never fit into a tutorial.
yeah, and now every interactable also needs to be a physics object. Which is fine, and maybe makes sense for other reasons for your game! Again, I think your solution is a good one. But I wouldn't worry that much either way
That’s still only a jumping off point.
Hopefully someone can help with this:
I have a GameObject, ButtonU, and I have a public variable that is set to ButtonU in a separate script. I want to access the 'isPressed' variable that is part of ButtonU, but I am not sure how. How would I do this?
Not a performant one. Physics is the best thing for anything related to spatial lookup that you get in unity. You would have to do a lot of work to improve on it.
.isPressed
I tried that
There's always a different way. Like Anikki said, I'm not sure I'd recommend any offhand, but everything is dependent on your game. If your game already has a chunk or room-based location system and the player is in distinct 'zones', you can tie items to their location and query them that way. If the player is only 'allowed' to interact with certain items and you already need to keep track of that, you can reference/activate those directly. etc etc.
Whatever you do, consider that spatial lookup (colliders and such) are a very intuitive, easy to understand way to organize a world. If your game is one where you walk around in a world, you can simplify many things by simply using space to separate and group things. Going down the symbolic route is often only neat in the beginning. Though it can be fantastic but you need a lot of experience to make the right decisions early on when you don’t yet fully understand what you need.
Space (noun):
the dimensions of height, depth, and width within which all things exist and move
(compared to, say, a card battler, where there is no real 'location' within which everything exists from the perspective of the game)
Let's say I want like entities to be able to have like status effects in sorta of like you have X effect for Y seconds AND this can be stacked (or reset the duration) and removed by external means. Would it be a good idea to make it like a separated script that I can attach to the entity for a given time and then remove itself when it is gone?
up to you, basically you have an ID for the effect and a stack count (and duration if those are not the same in your game). Then I would either do it OOP style where you have 'auras' which have OnApply/OnTick/OnRemove handlers, or 'systems' style where the auras are just data and you check for the relevant ones at the proper times
in either case you'd probably want one script which handles storing active auras for a given entity
you could also do it your way, but you'll run into issues where you need to do things like 'check if an aura is active and add stacks to it instead of attaching a new aura component' and it's nice to be able to write your own code for that instead of relying on the component system
Well, adding a stack would pretty much just mean adding a new instance of the script and removing them all or just one depending of the case if I do it in that way
hi guys! im making a breakout project for uni, and im trying to get the ball to bounce back in a random direction back at the player, but only for the first bounce cause once the direction is offset, it'll reflect like normal off of everything else
this is my orb behaviour code !
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.
How they make NPCs walk around and talk to main character? what is the best method to achieve this
So what's actually happening?
Where's the part of the code that handles when you hit the player?
both of your if statements have:
&& !collision.gameObject.CompareTag("Player")
so you are never handling player collisions
(ps you don't need the .gameObject there)
hold on lemme reread this, ive had some help from AI and im very very very tired just trying to get this last feature added lol
Seems like yes you need to basically just reread your code carefully because the logic isn't right
cause im not trying to do anything when it hits the player
im trying to do it when it hits ANYTHING else
so the process should look like this
shouldn't it reflect the same way it does on a wall for subsequent hits?
shoot - first bounce from ball - random direction back at the character - disable the random logic until the next fresh ball - ball will reflect off of everything normally
or actually - if I know breakout- the reflection angle should be based on which part of the paddle you hit
unless you're not doing that part
it should but it i shoot it straight it just bounces back and forth forever
i think im just gonna keep it simple cause its breakout
im trying to do my own 3d spin on it for the project
this logic seems overcomplicated for that
heres some visual context as to how this looks
shouldn't it just be:
bool firstBounce = false;
void OnCollisionEnter(Collision collision) {
if (!firstBounce) {
// bounce in a random direction
firstBounce = true;
}
else {
// do the normal reflection logic
}
}```
it doesn't make sense to me that you're doing any tag checking
Isn't the first hit always going to be a wall?
that bit wasnt me 😅
How could the first hit ever be a player?
Why are you using code you don't understand then?
ChatGPT is not magic
you can read and understand the code
its a mixture of both atm, I promise I will start actually understanding the code though
Like - it should be setting off alarm bells in your head if you see this:
// For subsequent hits (wall or player), reflect the velocity normally
if (!firstBounce && !collision.gameObject.CompareTag("Player"))```
The comment says "wall or player"
but the if statement specifically excludes the player
yeah that would make alot of sense
i did read that tbf but thought nothing of it for some reason
im probs just missing things cause its late
The other thing you should be doing is adding Debug.Log statements in your code
printing things like the tag or name of the object you hit and which code path you're going down
then you can reason about what's actually happening and going wrong in the code
it is very helpful actually when i do use it so im going to try and get into that good habit
ooo i have an idea,
would it work to have sorta rounded/slightly elongated shapes as colliders so it just changes the direction?
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
how could i change a vairble of a TMP text from another object/script
why is this not working? after reading everything idk why the viewcone is 90 degrees off?
public static void ViewCone(float radius, float viewInDegrees, Transform transform) {
var rotationRadians = transform.rotation.eulerAngles.z * Mathf.Deg2Rad;
var halfFOV = viewInDegrees * 0.5f * Mathf.Deg2Rad;
var leftDirection =
new Vector3(Mathf.Cos(rotationRadians + halfFOV), Mathf.Sin(rotationRadians + halfFOV));
var rightDirection =
new Vector3(Mathf.Cos(rotationRadians - halfFOV), Mathf.Sin(rotationRadians - halfFOV));
Line(transform.position, transform.position + leftDirection * radius, Color.yellow);
Line(transform.position, transform.position + rightDirection * radius, Color.yellow);
}
Looks correct to me.
What are you expecting?
the viewcone to be centerred on the green axis not the red.
am i doing something wrong? or what am i missing here..
so at angle 0 radians you will get (1, 0)
which is the red axis (x axis)
so it seems perfectly correct for your code
so yes the code is working for the red axis. how do i change to the greeen?
add 90 degrees or PI / 4 radians
to both the left and the right ?
you could also drop the trigonometry and do this:
Vector3 forward = transform.up;
Vector3 leftDirection = Quaternion.Euler(0, 0, -halfFov) * forward;
Vector3 rightDirection = Quaternion.Euler(0, 0, +halfFov) * forward;```
Just to the first line
which will apply to both yes
In fact I would highly recommend this because it means you won't depend on transform.eulerAngles which is itself a pitfall usually
like this?
public static void ViewCone(float radius, float viewInDegrees, Transform transform) {
Vector3 forward = transform.up;
var halfFOV = viewInDegrees * 0.5f;
Vector3 leftDirection = Quaternion.Euler(0, 0, -halfFov) * forward;
Vector3 rightDirection = Quaternion.Euler(0, 0, +halfFov) * forward;
Line(transform.position, transform.position + leftDirection * radius, Color.yellow);
Line(transform.position, transform.position + rightDirection * radius, Color.yellow);
}
If you do this you should remove the Deg2Rad from:
var halfFOV = viewInDegrees * 0.5f * Mathf.Deg2Rad;```