#💻┃code-beginner
1 messages · Page 505 of 1
I believe it does do that already
you just cant be tabbed into it, and you have to start the application
also may i ask why? thats kinda strange that you would want that
also this is not a code related question, or unity at all
Cache the local euler angle property, modify it then reassign it to the local euler angle property. For example: cs var lea = transform.localEulerAngles; lea.x = ... transform.localEulerAngles = lea;
Assuming you're simply having difficulties with c# properties relative to Unity's strange naming convention for properties - they're camelCase and not Pascal for some reason..
i assumed there would be like an Application.notifywindow or whatever
im talking about like my built project
thats a windows thing
not the editor
im talking about based on a unity event
like if youre tabbed out and you load into a game
you send an event or whatever
but as stated its not a unity thing
afaik
you can write your own code via c++ or python or something do mess with windows if you really want that
its most likely possible, i just dont know how
Would lea.x be the part where I clamp?
you can also clamp various ways using custom logic and such
i dont do that though
I probably should have gone straight to the documentation without asking
I'm just looking for a simple clamp 🙂
then use the documentation
where is a good place to ask about my ide?? everytime I open a script (at least i think thats whats happening) it looks like I can't use autocomplete. only way for it to show up again is reopening visual studio code. this is really getting on my nerves now :(
!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
ah I see what you meant, this isnt a code issue and you can ask in #💻┃unity-talk
oddly enough i've already followed all the steps for that. it works fine but every now and then it stops and I've gotta relaunch vs for the unity extension to work properly.
do you have VS and VS code installed?
yeah I do
that's why, remove VS Code
like uninstall the whole thing?
yep
he showed a picture of it and its autocompleting, looks fine to me #💻┃unity-talk message
alright i'll give that a shot thank you
the issue is that like it's not persistent. it ends up just ceasing to work every now and then.
The last line of this is stopping the rotation of my object
Vector3 pitch = transform.localEulerAngles;
currentMousePosition = Input.mousePosition.y;
mouseMovement = currentMousePosition - startMousePosition;
transform.Rotate(Vector3.right, -mouseMovement * speed * Time.deltaTime);
pitch.x = Mathf.Clamp(pitch.x, -30f, 30f);
startMousePosition = currentMousePosition;
transform.localEulerAngles = pitch;
Nevermind im a dummy, I rearranged everything to the top 🙂
why would you do a Rotate and set the eulerAngles at the same time?
Likely wanted to rotate first then validate with a constraint.
There is an issue where the object gets to 0 on rotation.x and then it jumps to the max clamp value
Euler angles acquired from the property (a Quaternion) would vary.
should never use eulerAngles as an input to a rotation and clamping the x makes no sense because you have no idea what it is
Your best bet is probably to keep the angle as a field in the class and simply write to the local property when necessary - never really reading from the quaternion using euler angles.
This isn't making sense to me i'm afraid
read from the localrotation of the transform
Quaternion pitch = transform.localRotation;
pitch.x = Mathf.Clamp(pitch.x, -30f, 30f);
transform.localRotation = pitch;
Like this?
Quaternions don't store angles in degrees, so that won't work
It did not work as said haha
One Quaternion can be represented by multiple different Euler Angles. So you shouldn't be reading from .eulerAngles at all, since the values you get can vary wildly
Store the rotation in a vector variable (or two float variables), and accumulate the mouse rotation into that. Then clamp and apply to .eulerAngles once
Is it possible to refrence a Monobehavior script on a Non monobehavior script
Yes, MonoBehaviour is a type like others
Just make a variable of that type (or the precise script type you need)
just keep in mind you have no inspector so you have to pass the reference somehow so its not null
Thats what I need I need a way to pass the reference
simple DI with a method
DI?
Or a constructor
You almost certainly want to use your actual script class and not MonoBehaviour
im detecting right clicks on objects in canvas
i instantiate a UI prefab
the parent has an image with 0 alpha, to detect clicks and there's children as shown
however when i right click the child image, it detects the child image first before detecting the image component on the parent gameObject
i understand this is the normal behavior of unity
but I want a clean way to change that.
this method returns all the item that the raycast passed through after i pass it the pointer click data
List<RaycastResult> GetClickedItems(PointerEventData eventData)
{
List<RaycastResult> results = new List<RaycastResult>();
graphicRaycaster.Raycast(eventData, results);
return results;
}
you also have the static functions like FindObjectOfType if you don't need specific one, or its the only one. Or use the array version loop through them to find specific thing. Using injection is always better (pass it through a method like constructor too)
What is the child? Does it need to be detected at all?
If not just disable Raycast target on it
I need a specific one of these scripts What way would I get that? a DI or constructor?
disabling raycast is not an option
as u can see, there's a button child
maybe explain what you're doing exactly , what is the gameplay mechanic
class Sample
{
public YourScript Script { get; }
// Constructor
public Sample(YourScript script)
{
Script = script;
}
}
// Usage:
Sample s = new Sample(someScript);
Simple constructor injection
cause one way or another you still need to grab that specific mb component, we don't know your setup so its hard to say how exact
even if you do .eulerangles.x/y/z?
So I want on click a state machine to switch states and I have a click Detector and when the isClicked = true I want it to run this is the code I just need the refrence
{
FarmGround.SwitchState(FarmGround.GrowingState);
Debug.Log("State Switched To Growing and Clicked");
clickDetection.clicked = false;
}
the reference to what exactly lol sorry ?
this script ?
you would pass clickDetection to the constructor / method to your non-mb class and store that there
still confused on why you're passing it for tbh
Should I store using .eulerangles or localeulerangles?
Vector3 pitch = transform.localEulerAngles;
Vector3 pitch = transform.eulerAngles;
For example or would it not matter?
Oh so I would do it from the StateManager then use it there got it that helps a lot and so it knows when to switch states
is this in update or something, maybe you want to look into events
What do you mean
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
So you want me to go along the lines of this?
Vector3 pitch = Quaternion.Euler(transform.localRotation.x,0,0 );
(This does not work at the moment so need to do more research)
Not that either
Store your rotation in variables
private float pitch; for example
Add input to that, clamp, build a vector or quaternion from that and write it to euler angles
Oh did you mean the actual rotation process? I thought you meant the object's current rotation
None of your code processes a "location" (=position), everyhting is a rotation
Yeah sorry, I was rushing. I changed it up
I don't understand your question
I'm not sure if you want the angle of the object or the rotating itself (transform.rotate etc)
Full angles are stored, not deltas (changes in rotation). Deltas are added to the full angles variables
pitch would contain the accumulation of all changes in rotation you've made by moving the mouse around
So im using a box colider2D to trigger a dialogue box, but when i go over it the first time it works but the i have to enter the collider 2 times before it triggers again....
any ideas why this would be happening?
It containing 45 would not rotate the object by 45° each frame, it would make the object point at 45° all the time
transform.Rotate(Vector3.right, -mouseMovement * speed * Time.deltaTime);
this is what I use to rotate the object, I should store this in Pitch?
This rotates by an amount, so it is not correct if you need to use a variable containing a full angle
I think getting the initial angle is where I am having the issue then
You don't get the initial angle from anywhere. You set it to 0 in the code directly
private float pitch = 0; (individual variables) - or - private Vector3 rotation = Vector3.zero; (all-in-one)
not without seeing the setup + code
Ah that's why I was getting confused, I thought we wanted to obtain the object's angle the whole time
No, for the 3rd (? - I stopped counting) time, I said that we do not read the rotation from anywhere
No I can't see that. The setup and the desired behavior are a little unclear
I understand it now, This value (not linked to anything) will increase/decrease in proportion to the increment/decrement done by the transform.rotate
By your mouse input*
Add mouse input to local rotation variable, clamp that
Write to object's location last. transform.localRotation = Quaternion.Euler(localRotationVariable)
Once! Do not use transform.Rotate() before or after since it'll overwrite/get overwritten by the one you just did
Nothing is on the Sign Parent, does this help @rich adder
This input or the input interface?
mouseMovement = currentMousePosition - startMousePosition;
Also thank you for being patient with me, I should have gone bed a while ago so my brain isn't braining
currentMousePosition = Input.mousePosition.y;
mouseMovement = currentMousePosition - startMousePosition;
transform.Rotate(Vector3.right, -mouseMovement * speed * Time.deltaTime);
startMousePosition = currentMousePosition;
pitch = Mathf.Clamp(mouseMovement, -3000f, 3000f);
transform.localRotation = quaternion.Euler(pitch);
This is what I have so far but i'm clearly not thinking when tired so I'm going to sleep. I will come back to it tomorrow. Thanks to the people who was patient and tried helping me out
so is the log "IS WORKING" printing when it doesn't open
My project works fine in the editor but no script load when doing a quick local build.
A scripted object (probably xyz) has a different serialization layout when loading.
After doing some research, this could be linked to using conditional compilation in script but this project is brand new and I don't use such directive in my code. Second problem could be myasmdefbut I've enabledAny Platformsand restarted my editor.
I don't know what to debug next. Could someone help?
when i make a new C# Script some of the code in my Player Scrpit stops working like [SerializeField] and stuff and for some reason i cannot use
player = GetComponentInParent<player>();
Why not, what's stopping you
Share the code of the script that appears in the error.
im not sure wahat is
So, no problems then, everything works?
no everything stopped working when i make a new C# Scrpited
So then what is the actual problem
Wdym by "everything sopped working"?
Can you be a bit more specific?
Does your computer shut down and your whole city gets a blackout or something??
no just nothing wants to compile anymore and functions i made in the Player script wont work in PlayerAnimEvents script
the second i made the PlayerAnimEvents script everything in Player Script just stopped working and wont let me compile
Ok, so you get a compile error?
yes and its from this code is what the error says
void Start()
{
player = GetComponentInParent<player>();
}
Share the actual error. You should have done it at the very start.
Assets\PlayerAnimEvents.cs(13,39): error CS0246: The type or namespace name 'player' could not be found (are you missing a using directive or an assembly reference?)
the thing is i have player in the same script
For starters, you should 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
Yes it is, but i figured it out so on the dialogue anim it takes a small time to put it back in position. So if u go to a new sign before it's all the way in position it won't pop up if that makes sense lol
Either way I did figure it out! Thankyou
yes in the Player.cs
Show it. At least the class definition line
This is Player. I asked if you had a class named player
like what you're trying to get from GetComponent
No you don't
oh my bad i sent that testing to see if lower would work
when i type GetComponentInParent it doesnt show like its not a known in VS
idk what i did but i fixed it but got a new error
MissingComponentException: There is no 'Rigidbody2D' attached to the "Platform (2)" game object, but a script is trying to access it.
You probably need to add a Rigidbody2D to the game object "Platform (2)". Or your script needs to check if the component is attached before using it.
UnityEngine.Rigidbody2D.get_velocity () (at <cba4ac0113cf44c9935a337fd866f6c7>:0)
Player.Movement () (at Assets/Player.cs:112)
Player.Update () (at Assets/Player.cs:50)
nvm
i fix
thx for the help guys
There is no Rigidbody2D attached to the "Platform (2)" game object, but a script is trying to access it.
You probably need to add a Rigidbody2D to the game object "Platform (2)". Or your script needs to check if the component is attached before using it.
i put the Player Script in the Platform(2) i didnt mean to
Having an issue with structure placement. One of the structures works perfectly fine, while the other constantly flies towards the camera, even though the code only adjusts the Y values.
Been troubleshooting this and can't seem to narrow down the issue, the code is attached. It froze at the end because I placed it.
Also lag is due in part to game running in background.
Found the issue, the raycast was hitting the cube. Not sure why the same wasn't happening with the cannon though, but after deciding to try a new layer anyways, it worked.
hello, does anyone know why this happens? i thought i checked for missing teamControllers
the first screenshot was bad actually hold on
Seems like you have some code accessing a destroyed object
You're doing ship.transform
You can't do that if it's destroyed
You would need ship == null as the first condition
You're doing it after the dangerous stuff
The order of the or statements in the if code matters as they are processed left to right
Is there a limit to the amount of corners that can be generated from NavMesh.CalculatePath?
Hmmm. Probably not. Going to elaborate further in a second
So here's my problem:
Blue filled in square at top left is destination. There is a blue wireframe cube at the bottom right that is the beginning.
The gray spheres are nav mesh corners. The blue wireframe cubes are the nav mesh corners being translated into grid nodes.
Strangely, my issue isn't with the wireframe cubes, but the spheres. As you can see, they kind of, give up before the end destination. These are nav mesh corners. And I have no idea why they're just... giving up before the end destination.
https://youtu.be/Xf2eDfLxcB8?si=e5ShyBqMwqMahRtZ
i was watching this and did this but it dosent seem to work can anyone help me?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine..ImputSystem
public class PlayerJump : MonoBehaviour
{
[SerializeField] private ImputActionProperty jumpButton;
[SerializeField] private float JumpHeight = 3f;
[SerializeField] private CharacterController cc;
[SerializeField] private LayerMask groundLayers;
private float gravity = Physics.gravity.y;
private Vector3 movement;
private void Update() {
bool _isGrounded = IsGrounded();
if(jumpButton.action.WasPressedThisFrame() && _isGrounded){
Jump();
}
movement.y += gravity * Time.deltaTime;
cc.Move(movement * Time.deltaTime)
}
private void Jump() {
movement.y = Mathf.Sqrt(JumpHeight * -3.0f * gravity)
}
private bool IsGrounded() {
return Physics.CheckSphere.(transform.position, 0.2f, groundLayers);
}
}
Learn how to JUMP in VR using Unity's XR Interaction Toolkit. In this video, we create a new script for our Player and implement a jumping mechanic for our player using Unity's Character Controller!
Previous video: https://youtu.be/mYhVNtRGAhw
Get the source code: https://www.patreon.com/posts/unity-vr-source-88131424
// JOIN THE COMMUNITY DI...
"ImputSystem"???
Double check your code for typos and misspellings
!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
make sure to delete your double post from the other room too
ookk
@near wadi i got this from this web https://paste.ofcode.org/g9NRYjQwrKs6CFEn4F5V6V and it still dosent work idk if it fixes it for you or how it works i am very new to unity codeing
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine..ImputSystem
public class PlayerJump : MonoBehaviour
{
[SerializeField] private ImputActionProperty jumpButton;
[SerializeField] private float JumpHeight = 3f;
[SerializeField] private CharacterController cc;
[SerializeField] private LayerMask groundLayers;
private float gravity = Physics.gravity.y;
private Vector3 movement;
private void Update() {
bool _isGrounded = IsGrounded();
if(jumpButton.action.WasPressedThisFrame() && _isGrounded){
Jump();
}
movement.y += gravity * Time.deltaTime;
cc.Move(movement * Time.deltaTime)
}
private void Jump() {
movement.y = Mathf.Sqrt(JumpHeight * -3.0f * gravity)
}
private bool IsGrounded() {
return Physics.CheckSphere.(transform.position, 0.2f, groundLayers);
}
}
please understand what you're trying to code rather than copypasting stuff from the web
i watched a vid and it got it wrong so i did the fix web thing
still dosent work
chatgpt doesn't work in 2024
You ignored all the advice from above
generative AI has shat itself so hard it's now unuseable
lol it was a vid
please understand what you're typing
don't copy paste from videos either
ok so what are you trying to do
im trying to make a jump system for vr players
If they had copied and pasted there wouldn't be such blatant errors
Configure your IDE as mentioned above and fix your typos
what is ide
Integrated development environment.
It's the app you use to type your code.
Visual Studio and IntelliJ are examples of this
You may be prompted to install Visual Studio when installing unity
i use vis stuido
#💻┃code-beginner message so click vs and follow steps
In this message click the first link.
i did steps now what
bro what am i sopse to dooo
show your ide is configured
thats not even close
to being configured
also you did not show the IDE
what thats what it told me to do
so why does it say here Visual Studio and yours says Visual Studio Code and a bunch of args underneath?
Why doesnt it say Visual Studio, and show also the Visual Studio Editor package version
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
My visual studio won’t open… anyone know why?
How are you opening it?
I’ve tried double clicking the script in my unity, doesn’t work, I’ve tried opening it through my home, doesn’t work
have you tried reinstalling
Sadly no cause I’ve had no time, do you think that’ll fix it?
if VS won't even open as a standalone application it's your best bet
that's not a unity issue that's a VS issue
And when I got unity that’s when it started buggin
weird
Yea
have you tried taking a hammer to your PC out of frustration? /j
I’ve thought of it… but no
I really don't think the code of the script is relevant. I only have two scripts which both trigger the error in the logs
NetworkUI script (one of the two scripts): https://paste.ofcode.org/deJtHmHbNx5FNjFY7FngSh
Log of devbuild: https://paste.ofcode.org/c8D5AgKjTTxkdX4nNyJLY8
asmdef: https://paste.ofcode.org/LAZAQP2EQiwRGL4J5RRr6P
Share the error details as well
The error details are the one in the devbuild log, this is the only info I have with the freezing build (which is normal if no script are compiled)
Does it work if you take NetworkManagerUI out of the Project namespace?
Hello
By work, I mean, does the error regarding NetworkManagerUI disappear?
Could someone teach me how to make a teleport script when clicked with handtag?
Removing the NetworkManagerUI script entirely makes everything build again.
And the controller script works fine
Not removing entirely, but taking it out of the namespace.
Also, do you reference that script anywhere?
wdym by reference? I had attached it to a NetworkUI GO but that's all
Only removing the namespace Project ?
what the hell, I've just added the script back and built again and everything works perfectly. i've banged my head for 2h yesterday on this
helloo friends im getting following error while pushing my changes to remote repo
remote: error: Trace: ad2bd1b3597d974fd51d57b7eba80e30835602055d1b319384538a043f7c1883
remote: error: See https://gh.io/lfs for more information.
remote: error: File Library/PlayerDataCache/Win64/Data/sharedassets1.assets.resS is 157.50 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File Library/PackageCache/com.unity.burst@1.8.16/.Runtime/libburst-llvm-16.dylib is 124.60 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
To github.com:Bloom56/Orbit-Runner.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'github.com:Bloom56/Orbit-Runner.git'
Please help me resolve it
How do i exclude this library file
i think unity is generating it automaticaly
You should put /Library/ in your .gitignore
!vcs
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
Your gitignore doesn't have the standard Unity stuff in it (like /[Ll]ibrary/), and committing those files is not only unnecessary, but also unreasonable
the problems is i have made some changes in project that are also not getting commited
should I add /[Ll]ibrary/) this in gitignore
You should be adding everything from the gitignore linked above to your .gitignore
Unless you've added something custom, your gitignore should 1:1 be that file
Can i move ui components with code?
can someone help me with this
And the code?
So what i can tell you are trying to destroy an object
And unity is stopping you becouse
why tho
do i build it and run ?
Error
coz im making an apk
Well what are you destroying?
I think unity is trying to tell you that when you destroy them there will be no way to call it back
this ?
Yeah
what if i use build and run
how i forgor
i havent touched unity in like a year
when i reference a GameObject, is has to come from Hierarcy, right? i would not be able to use the 'parent' prefab from the Project
ill brb
are you trying to destroy something in edit mode intentionally?
lemme send screen recording
this doesnt make a ton of sense imo, you can reference a gameobject thats a prefab.
why? i asked a simple yes or no question
that is what i thought, thanks. due to the way this asset is coded, it allows the reference, but ignores the trigger. i am just trying to write my own trigger at this point.
then you should read the error and reconsider what your code is doing. your code is trying to destroy something in edit mode when you say you dont want to
Is that a script that you wrote or from an asset?
its not mine (i got it from a game and im making mobile port, also we have permission to do this)
Got it from a game as in ripped it?
using assetripper yeah
We can't help with that, even if you have permission
yeah thx tho
can anybody help me with my dash function? for some reason the dash is only vertical and not horizontal
my code: https://paste.ofcode.org/cENBMendFEdJskQai5vfEC
Your movement code in FixedUpdate overrides horizontal velocity
how should I do it?
is there a way to update velocity in a way that wouldnt override somthing else?
+=
Either use AddForce instead of setting velocity directly or don't set the velocity while dashing is happening
Reminder that you may need to remove the second argument
what do you mean by that?
I prefer to use vectors instead of forces
it feels more natural
playerRB.linearVelocity += new Vector2(speed * horizontalInput * Time.deltaTime, 0f);```Edited. You'll need to rework some stuff as this'll make you accumulate horizontally velocity.
why? dont I need to keep the upwards velocity?
Hmm, is there any context to solve this sort of issue?: Assets\MainGameProject\CharacterController\Scripts\PlayerLocomotionInput.cs(7,79): error CS0146: Circular base type dependency involving 'PlayerLocomotionInput' and 'PlayerLocomotionInput'
Following a video tutorial from here: https://youtu.be/muAzcpAg3lg?si=IptL5gCbyegydth6&t=799
But I changed the PlayerControls on my Input System to PlayerInputSystem for organizational reasons. Did I break something in turn?
Code link: https://hastebin.skyra.pw/cuqudodewe.csharp
In this series, I'll be going over beginner through advanced topics for building a complete player controller, both for 1st and 3rd person. We'll covers topics like movement, jumping, slopes, wall handling, step handling, animation, blend trees, Mecanim, Cinemachine, avatar masks, animation layers and multiplayer.
This is a free complete course...
you are referencing the class as a type of itself. Are you sure, thats what the tutorial was suggesting to you?
no they aren't
well, maybe, but you wouldn't be able to see it in that screenshot
the screenshot shows a nested interface
the ide doesn't look set up, you have no diagnostics
the class already inherits from MonoBehaviour, you can't inherit from multiple classes
the error would be different
where is PlayerLocomotionInput.IPlayerLocomotionMapActions coming from? it doesn't exist in the code you linked
its an interface he tries to inherit from, but as he tries to get it from the class itself AND its not there, it wont work. thats why I suggested him to look for his source of code again. rhetorical question more or less
But where is that interface you are trying to implement here?
you just changed it? D:
It says playercontrols in your screenshot
{
MovementInput = context.ReadValue<Vector2>();
print(MovementInput);
}```
in your own code, it says PlayerLocomotionInput. Take care of what you are doing
Ok
Following a tutorial without thinking will leave you without any additional knowledge when finished
Ok
Head's up for an update:
Assets\MainGameProject\CharacterController\Scripts\PlayerLocomotionInput.cs(7,57): error CS0535: 'PlayerLocomotionInput' does not implement interface member 'PlayerInputSystem.IPlayerLocomotionMapActions.OnMovement(InputAction.CallbackContext)'
If your !ide is properly configured you can call quick actions on the interface and implement it
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
It doesn't automatically generate the Interface as far as I know of.
do what fusedqyou linked, presumably for vscode. your ide doesn't have diagnostics, you need to set it up
Judging by the screenshot it looks configured, so I'm confused why you'd have an issue here
judging from this one?
definitely not configured
that one's from the video
The first one is not configured, the second one is
Then it's not configured
I'm surprised nobody mentions their ide must be configured then
i did
I'm working it on Parallels Windows through a Mac.
Mac should work the same. Make sure your ide is configured before you do anything
Its installed BTW
This might have something to do with it:
Cannot find .NET SDK installation from PATH environment. C# DevKit extension would not work without a proper installation of the .NET SDK accessible through PATH environment. Rebooting might be necessary in some cases. Check the PATH environment logged in the C# DevKit logging window. In some cases, it could be affected how VS code was started.
Sorry, no idea.
VSCode is generally not the best solution when it comes to Unity development
works well for me
but i also use vscode for all my development
so i know how to deal with a lot of its quirks :p
all you have to do is install .NET Sdk, usually restart PC after for PATH issues to be fixed
is it possible to split a class into several files and have partial classes in them?
I tried but It's not possible to assign as a component anymore
absolutely
how big is it that you need to split it so much? might be a design issue there..
How?
I had the class in one file and could assign it fine..
then I split it into 3 files and made them all partial class but I can't assign it anymore
it does a lot of things that are interconnected.. breaking it up into multiple classes would introduce a lot of overhead and boilperplate
ehh easier to manage smaller components than monolith even if its split into multiples
maybe you have initial friction but the benefit pays off ten fold
I tried it with an empty monobehavior class and it actually works.. not sure why it doesn't with my actual class
MyScript.cs
using UnityEngine;
public partial class MyScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
MyScript1.cs
public partial class MyScript
{
}
ah this is it. the "unifying" one can't have monobehaviour..
thank you!
yes, only the 'main' class should have inheritance
hi... why is it not working?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You wanna read this anyway -> https://unity.huh.how/physics-messages
using System.Collections.Generic;
using System.Threading;
using Unity.VisualScripting;
using UnityEngine;
public class destroylll : MonoBehaviour
{
public GameObject aaa;
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
Destroy (aaa);
}
}
}
slick new preview
has this link ready you beat me to it 
go through the link sent to you
fyi. just saying something is 'not working' does not help anyone
👍
always describe , what is supposed to happen vs whats happening instead
along w showing the setup ofc
Use CompareTag instead of comparing with ==
Won't fix your issue, but get used to this habit ASAP
I suggest you start by looking if the method is being called with a log message. If not, follow the steps from the site that was linked.
what was the issue?
Hi folk, I have a technical question. why is SetActive so expensive? GameObject.SetActive() 2x in a single frame just consumes 0.3% CPU
is there a way to minimize it's usage?
I just want to stop it's ticks etc, so I can actually stop it's ticks manually and teleport it far away
I guess it's going to be more effective?
when this runs 40 times a frame, the usage is %6 cpu. So that's the problem
I'm using an object pool to minimize the effort of spawning an object, but enabling/disabling is not cheap as well as I see?
Line 83 should be RemoveListener right?I'm not sure...
*A official sample(fps microgame)
I think a object pool will be better.
If your question is "Should I make sure to unsubscribe listeners?" then the answer is yes.
Because if you don't, then the reference will persist and call the listener each time it is invoked
Ok great,so that official got a mistake i think...
I'm already using an object pool. Though I still need to enable/re-enable inactive objects
if course there is overhead from doing nothing to doing something
what you're doing when those are active is more important to look at
Activating a GameObject calls OnEnable for each MonoBehaviour and continues to run their Update method(s). You can enable/disable specific scripts to start/stop their code from running, but you need to compare that performance to deactivating the GameObject . . .
Where did you get that number from? I have never seen a CPU percentage in the profiler as far as I remember
In the profiler: CPU Usage => Main Thread => Total Percentage of the function
I guess its the CPU Usage, no?
and that would be the cpu usage allocated to this process, not of your complete cumputer
I can’t get the screenshot cause of how fast the code runs, but mostly the collisions are detected up to a certain point, when the console doesn’t print the right tag anymore as shown in the video
Sorry for the late response
lmao "late", that was 5 days ago my guy. you can still screenshot it to show what happens even if the console is printing things quickly
5 days is a stretch
2 days whatever
Alright I’ll try
Hollup
right click it. also not a code question
Ah you mean that one. I though you meant CPU usage the same way you see in task manager. That isn't really an absolute measurement so would definitely look for the ms time instead and compare it to the frame budget you are having. If you are aiming at 100 fps, you have 10 ms to spend (not only for scripts of course) each frame for example.
Sry
@vernal spear regardless what you showed sounds quite much. It would require seeing the code and more of the profiler view to make sure you are not misinterpreting something or doing something in the code that makes it slow other than the SetActive call
after hitting the top wall it stops registering collisions in the console, ie works until 5th picture
screenshot the console window
why am i getting unassigned reference exceptions? its literally assigned there.
you have an instance of that component in the scene with that variable unassigned
Thanks for the information! For now it's not problematic since enabling/disabling doesnt happen quite frequently
You'd need to share more context, such as the code
You just have Collapse turned on in the console
It's working fine I think
so as i guessed 2 days ago when this issue initially started, your console is set to collapse so you aren't seeing the subsequent correct collisions
ohh yea thanks
thank youu
so now you need to look at your code and debug the values you use to see why it behaves the way it is
reflection doesn't work though
alright
using my initial code or with reflect?
the current code that uses Vector2.Reflect
use the log message I gave you as an example of how you can print multiple pieces of data in one log and print all of the relevant values to ensure they are what you expect them to be
look at your code to find out
i see it now, thank you
wow horrible screenshot
but you get the idea
if I print the initial launch's vector and then print the reflected vector would it work? and if i do that do i print the reflected vector on enter or on exit collision
print the values where you are going to use them. there's no sense in printing them in other methods, you need to know what they are at the time you use them so you understand what is happening
this is what I did
I printed the values and it printed wrong values
not what I expected
that's not helpful because you don't see the inputs you use. you aren't seeing the normal or the velocity before you assign it
recently learnt this lovely little operator
nice fallback if i ever forgot to set something in the inspector
except it does not work with unity objects and should not be used with them
would I say it didn't if I didn't mean it?
why doesnt it work
no, unity has overridden the == operator to handle destroyed objects when comparing to null. but the null operators like the null coalescing you are using do not use the overridden operator, so if an object is destroyed it will be == to null but not actually null
hi... how to make a block is visible after touching a block? "correctly and its working" some link or script? for this. im beginner
because Unity handles null references differently than standard c# for it's objects
i need it 
oh okay, thank you for the helpful answer
i guess thats what this means then
yes
and what next?
correct, the null operators all do pure null checks. there's not typically a reason to override how null checks work, but since unity objects are created on the c++ side of the engine and can be "destroyed" there needs to be a way to represent that on the c# side which unity decided to make == null represent that
if (other.CompareTag("Player"))
```
also note that there is no way for a variable to be automatically set to actual null so these objects are not actually null, they are "fake null" which means they just compare to null using those overridden operators
i found somethink
using System.Collections.Generic;
using System.Collections;
using Unity.VisualScripting;
public class turnon : MonoBehaviour
{
public GameObject Player;
void OnTriggerEnter(Collider Enemy)
{
if (Enemy.tag == "Player")
{
Player.gameObject.SetActive(true);
}
}
}```
its not working
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
ive tried making u a cool graphic for this..
too much info to fit in a good size constraint lol
Just do Brackeys in a Charlton Heston getup holding stone tablets with the commandments on them
- u probably got a copy pasta template
good plan. I have here these 11, oops, 10 commandments on Unity Physics Queries
Hey yo! I hope everyone is doing well this fine Monday. I was wondering if someone can point out my mistake? I am trying to clone Pong. I am trying to add sound and SFX. I have been able to get the backgorund music working and the sound when someone scores. What I am missing is getting the bounce sound to play when the ball bounces off of the players and the edge of the screen. I have tagged them all on layer 7. I have tried to copy the code that makes the score sound work. I am just not getting it to work. Would anyone be able to point me in the right direction?
Considering the first function is for a 2D collision, and the second one is not, I'd guess that at least one of those is wrong
Unless you're mixing 2D/3D physics, in which case, stop
LOL, I am not trying to mix them. I tried the to copy the top one, but it did not work either.
Right on, I will dig into this. Thanks
nice theme
let's say I have a rectangle with 4 triangles. I assign the second triangles as the first submesh and the third triangle as the second submesh.. what happens to the indexes?
seems to me they're getting jumbled?! is it [1, 2, 3, 4] -> [2,3,1,4]?! (always + the 2 following ofc)
Why do you have 4 indices in a triangle?🤔
a rectangle with 4 triangles
Ah, so it's not the vertex indices.
Then I don't understand what you're trying to say or ask.
I want to know how the indexes of the triangles get reassigned in mesh.triangles when I assign the submesh
Assuming you want a quad out of 4 triangles(with a vertex in the middle), you'd have something like 012 023 034 041 assuming 0 is the one in the middle. And I don't think submeshes are relevant to that at all🤔
Hey im making a point system and the question is how can i move the ui component along the canvas?
uning the set ofc
hm.. I realize my question is wrong..
when I assign a material to that submesh.. what are the indexes for the vertices or triangles in that submesh (for the material or rather the shader)
Each submesh is like an individual mesh, so it has it's own triangles array.
and the triangles I pass in get reindexed from 0 then I guess?
Should be, yes.
Actually maybe not. According to this page, they might be indexes into a shared array of vertices.🤔
https://docs.unity3d.com/ScriptReference/Mesh.GetTriangles.html?utm_source=perplexity
I guess the best way to tell is to test it out.
yea.. been testing out for a while now :>
but I always used .triangles
gonna try using .GetTriangles(submeshIndex)
rect transform
Thanks, even though I am not sure what theme that you are talking about.
the color scheme of the IDE ur using
very matrix'y
it matches my keyboard on my phone.
ohh.. that ruins it a bit 😛
Maybe you can tell me what I am doing wrong again or point me in the correct direction. If I add the if statement for a layer 7 collision it works when the game objects are checked at triggers. The problem this makes the ball pass right through and not bounce off. If I remove the is trigger check box. The ball bounces but the sound does not play. How do I get both to work? I have even tried to do a separated at the bottom but it does not work at all.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if OnCollisionEnter2D was not working at all, then you need to go through this: https://unity.huh.how/physics-messages
OnTriggerEnter2D is meant for trigger overlaps, which means any collider overlapping a trigger collider (which is not solid on account of it being a trigger)
OnTriggerEnter2D calls whenever a trigger collider is interacted with by a rigidbody.
OnCollisionEnter2D calls whenever a non-trigger rigidbody collider interacts with another non-trigger collider.
If either collider is marked trigger, that collider is non-solid and will not stop movement in any way
i cant seem to get the unity syntax extension working in visual studio
The scoring trigger worked. They played a sound and added one to the score. It is just the layer 7 one that is not working. It works if I mark one as trigger. Let me try to write it with OnCollisionEnter2D.
I got it working. Thanks for the help. I think I just had sometime identified wrong.
hello, does anyone know why this code isnt working? https://paste.ofcode.org/Y8HXCNFfPvgY5qH52NTabD
which one did you use ?
pasting it here in case it was because of a dumb mistake because i can't figure out anything wrong with it
be more specific than "isn't working"
i just selected the unity option when installing visual studio
are you talking about VS or VSCode
!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
you installed the Unity workload you mean?
idk im new to this
click the guides above
make sure you do each steps
regen project files after the steps, it will refresh it
(you will see the button for later use in one of the steps)
its fine if i use vscode right? i was gonna use vs since thats what it defaulted to but if i can stay on vscode id like to
they both work fine
as long as you configure them properly
okay, thanks!
in the code it is supposed to reject missiles tagged as "MissileTeamTwo" if the bool ScanForMissileTeamOne is set to true, and vice versa, however it still adds targets tagged as "MissileTeamTwo" if its scanning for missileteamone
well for starters you should be using the CompareTag method to check an object's tag rather than .tag ==. second, what debugging have you actually done?
i followed every step and it still doesnt work
i sprinkled debug logs in every if function in the IsTargetValid function, however they said that it was scanning correctly (if ScanForMissileTeamOne is true and the missile was tagged as MissileTeamOne it printed a log to the console) however it also said that it was ONLY seeing missiles tagged as MissileTeamTwo
like, it doesnt recognize unity's syntax
did you regenerate the project files?
how do i do that
go through the guide and complete every step. you'll see the button if you actually do that
then you did not complete every step
restart visual studio after doing so
if it is still not working then screenshot three things and show them here: 1. your external tools settings. 2. the vs editor package. 3. the entire visual studio window with the solution explorer visible
sure
oh look, you didn't complete the steps.
i did tho?
This is VS Code btw, make sure you selected the correct link
as it says here, You're missing the .NET sdk
vscode requires this to work properly with unity
and how am i supposed to know that if its not written on the one page meant to explain how to use it
it says "Installing the Unity extension installs all its dependencies required to write C# with Visual Studio Code, including the C# Dev Kit." but apparently not
(this is also in the vscode output btw)
The command could not be loaded, possibly because:
* You intended to execute a .NET application:
The application 'restore' does not exist.
* You intended to execute a .NET SDK command:
No .NET SDKs were found.
Download a .NET SDK:
https://aka.ms/dotnet/download
Learn about SDK resolution:
https://aka.ms/dotnet/sdk-not-found
yeah but it tells you here
and I agree its an oversight on their part but its something we must live with
so how do i do this?
VS does the same shit except it installs it for you
go to the website linked in the message?
make sure its the SDK not the runtime
restart PC after install. if it asks to modify path make sure you check off YES
idk last time i tried to manually install an SDK it was hell to find where i was supposed to put it
the default folder is fine..
it was for java, it didnt come as an installer i had to find where to put it
Hello, do you know if i can simplify this animator ?
restarting rn
blend trees maybe?
also not a code question
what is this
thx
still doesnt work, it now outputs
A JSON parsing exception occurred in [C:\Program Files\dotnet\sdk\8.0.402\dotnet.runtimeconfig.json], offset 0 (line 1, column 1): The document is empty.
Invalid runtimeconfig.json [C:\Program Files\dotnet\sdk\8.0.402\dotnet.runtimeconfig.json] [C:\Program Files\dotnet\sdk\8.0.402\dotnet.runtimeconfig.dev.json]
close vsc rq
okay
can you screenshot your External Tools page in unity
try clicking Regen Project Files and double click script again, wait a few sec
nope, still same error
open command line and paste this dotnet --list-sdks
show the output
it outputs this again
you restarted the entire PC ?
yup
im trying to to google this error because I never seen it before tbh
Ive set up VSCode so many times this is some new shte lol
try maybe installing an older version of .NET SDK maybe
.NET 8.0
8.0.8?
is your vscode updated to latest
i have version 1.94.0, lemme check if thats the latest
try an older version of .net patch, like this one
https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-8.0.107-windows-x64-installer
honestly, if you cannot get vs code configured then consider switching to visual studio. it's much better.
okay, it is
true
would yall mind helping me set it up if i do?
btw when you typed dotnet command was it done in the windows terminal not in vscode right?
yea
that goes over the entire process, including installation
i meant if i had other issues again, but thanks
but that raises a good point, the fact that the error doesnt come from vscode probs mean i'll run into the same issue in visual studio
you will be unlikely to have other issues because unlike vs code, visual studio doesn't require a lot of extra setup
iirc VS has its own dotnet isolated that it works from so there is usually no issue
just make sure you got the Unity Workload for VS Installer
thats the option you gotta select while VS installs?
yea, the VSCode one is more raw and uses the dotnet command (usually can use this to make a new ,net app via command line)
look at the steps you will see it
can i disable the shitty autocomplete
do you mean intellicode? because if so, then yes. if you mean the regular intellisense, that is not recommended
like, this
well that's not the auto complete, what's below it is. and that is intellicode.
how do i remove/disable intellicode
okay lol
okay its all good!
thank you so much
thank you for telling me what it's called, I hate that so much
okay now im even more confused, its returning as true even though the conditions mean it should be returning as false
private void Start()
{
StartCoroutine(SpawnEnemies());
}
private void FixedUpdate()
{
}
IEnumerator SpawnEnemies()
{
yield return new WaitForSeconds(3);
SpawnEnemy();
}
void SpawnEnemy()
{
StartCoroutine(SpawnEnemies());
}```
is there any better way to start the couroutine right after it ends?
why not just use a while loop if you want to make it keep going?
that means one of your if statements that returns true is true.
don't while loops run every frame? I just need to spawn an enemy, wait 3 seconds, and then spawna nother enemy
okay wtf, it worked before but i reopenned vs and now its not working anymore
make sure it is set correctly in External Tools and regenerate project files
Before any of these if statements, add this log:
Debug.Log($"ScanForMissileTeamOne: {ScanForMissileTeamOne}, Missle's Tag: {missile.gameObject.tag}");
And show what it says
that's why you put the wait 3 seconds inside the loop
While loops run to completion. If it's in a coroutine and you have a yield statement in the loop, it'll wait before resuming
i can wait inside a loop?
You can wait in a coroutine
note i am referring to putting the loop inside the coroutine, not where you start the coroutine
by before do you mean like this?
wait whaat
Just the once
before any of these ifs
IEnumerator SpawnEnemies()
{
while(true){
SpawnEnemy();
yield return new WaitForSeconds(3);
}
}```
Okay, so, looking at the logic, that should return false
I agree
how have you confirmed that it is not
what do you mean
well you claim that it is returning true, right? how have you confirmed that
How do you know it's returning true
its executing a block of code that should only be ran if its true, i'm adding a debug log to that block
show the current code, including how you are verifying that it returns true when it should not
do i need to do this every single time i create a new script?
no
every time ive created a new script it broke and i needed to regenerate them for it to work again
how are you creating the scripts?
going into the components, and crating a new script
just to confirm, you mean you are selecting the option to create a new component from the AddComponent menu in the inspector of a gameobject?
yup
have you done something silly like disable unity's Auto Refresh?
i havent touched that, so i doubt it?
humor me and check, it should be in the editor settings in preferences
I have this strange issue. I'm trying to bounce a projectile off of a wall, however, sometimes, it bounces off at weird angles/ignores the Normal?.As shown in the screenshot. The green trail is the projectiles actual movement, the minor red line is the raycast debug. The actual code for getting the reflect is the following, please ignore the weird Utils/other things, I was attempting a few different solutions
The weird thing is, it looks to be getting the inside of the mesh, and not the outside of it, causing it to reflect downwards instead of off the wall like I'd expect.
RaycastHit[] hits = Physics.RaycastAll(transform.position - transform.forward, transform.forward);
foreach (var hit in hits) {
Debug.Log("Hit: " + hit.collider.gameObject.name);
if (Utils.WillLayersCollide(gameObject.layer, hit.transform.gameObject.layer)) {
Vector3 hitNormal = hit.normal;
Debug.Log(hitNormal);
Vector3 bounceDirection = Vector3.Reflect(rb.velocity, hitNormal);
rb.velocity = bounceDirection;
Debug.Log("Bouncing");
return;
}
}
RaycastAll does not guarantee an order for the returned hit objects. is there a specific reason you are using RaycastAll for this and not just a regular Raycast to get just the first hit?
in here?
in the Asset Pipeline section
No specific reason, however, what you mentioned is probably the reason
nope, its correctly enabled
the close visual studio and restart the unity editor. after that open the External Tools section and let me know if Visual Studio is still assigned as the external script editor.
oke
yeah so you should probably switch to the singlular Raycast method and you can pass a layermask to that raycast to ensure you only get objects that it can collide with instead of looping through each one and manually checking using that Util function
yup, it still is
okay then go ahead and try to see if it's working now
it is working rn, lemme see if it still works if i create a new script
nope, doesnt work
creating a new script breaks it, and i do need to regenerate the project files
Yeah I was running into an issue with the Masking, as I was hoping to get it dynamically.
I see, thank you!
Still happening with the following.
RaycastHit hit;
if (Physics.Raycast(transform.position - transform.forward, transform.forward, out hit, 10f, Utils.GetCollisionMatrixLayerMask(gameObject.layer))) {
Vector3 hitNormal = hit.normal;
Debug.Log(hit.collider.gameObject.name);
Vector3 bounceDirection = Vector3.Reflect(rb.velocity, hitNormal);
rb.velocity = bounceDirection;
Debug.Log("Bouncing");
return;
}
Where the util is
public static LayerMask GetCollisionMatrixLayerMask(int layer) {
LayerMask collisionMask = new LayerMask();
for (int i = 0; i < 32; i++) {
if (!Physics.GetIgnoreLayerCollision(layer, i)) {
collisionMask |= (1 << i);
}
}
return collisionMask;
}
And for reference the collider on the wall is just a good ol cube.
I need two physics GameObjects to detect each other's collisions but not interact / apply force to each other. I'm currently trying every combination of collider and rigidbody to no avail. The game is 2d.
okay I fixed it, projectile is trigger now
yeah projectiles should be triggers, and any other object that shouldnt have a physical collision but can still run OnTriggerEnter
hi all, I'm making my way through cs course for beginners, got stuck on setting axis frame for a cube guy. This is the error I get " Assets\Scripts\Player.cs(35,66): error CS1003: Syntax error, ',' expected " I tried to retrace my steps but nothing worked...what did I missed? ```public class Player : MonoBehaviour
{
public float speed = 3.5f;
void Start()
{
transform.position = new Vector3(0, 0, 0);
}
void Update()
{
float verticalInput = Input.GetAxis("Vertical");
float horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.down * verticalInput * speed * Time.deltaTime);
transform.Translate(Vector3.left * horizontalInput * speed * Time.deltaTime);
if (transform.position.y >= 0)
{
transform.position = new Vector3(transform.position.x, 0, 0);
}
else if (transform.position.y <= -3.8f)
{
transform.position. = new Vector3(transform.position.x, -3.8f, 0);
}
if (transform.position.x >= 11f)
{
transform.position = new Vector3(transform.position. -11f, y, 0);
}
else if (transform.position.x <= -11f)
{
transform.position = new Vector3(transform.position. 11f, x, 0);
}
}
}```
what line is 35
On line 35 it expects a ','
Does anyone know what might be the cause of this mouse jumping?
I have a player empty gameobject with a movement script on it and a character controller, then I have a body inside of that which is just a capsule with a collider, then a camera in the body.
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cameraTransform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
transform.Rotate(Vector3.up * mouseX);```
Don't multiply mouse input by deltaTime, it's already framerate independent
(You will almost certainly need to adjust your mouseSensitivity value after making this change, it'll be much faster)
this is the one
that fixed it lol thanks
Yeah, that's not valid. What's transform.position.11f?
'round these parts we call it "The Brackeys Error" because he did it in an early video and everyone just copy-pastes his code for their tutorials and we're still dealing with it to this very day
damn 😭
you can do transform.position.x + 11f, x //this is the y float of a vector so i dont know why you have x here, 0 if you are looking for an offset. fixed it I got a little mixed up
darn brackey
I remove space there, it didn't work
you need a ,
It's not the space that's the problem. C# removes all extraneous whitespace anyways
also thats not valid code
transform.position.11f is not a thing
The space isn't the problem, you need to access the member you want to access
i gave an offset example if this is what you are looking for #💻┃code-beginner message
i have zero clue of what you want though
transform.position.(x/y/z)
Does anyone have an idea as to why the following code would give me a NullReferenceException for line 7?
2
3 void Start()
4 {
5 foreach(EnemyBrain enemy in FindObjectsOfType<EnemyBrain>())
6 {
7 enemyList.Add(enemy);
8 }
9 }```
enemyList is null
For the same reason any other NullReferenceException happens. You tried to dereference a null reference.
When you use the ., you need to make sure the thing on the left side of it isn't a null reference.
All references start out as null and will be null unless you assign them somehow. Either in the inspector or with the = operator
Your reference here is private, so the inspector is not an option. Therefore you have to assign it somewhere with the = operator
If my object has a velocity, will its position be different between the Update and LateUpdate calls to a script?
Do you mean a Rigidbody, or something else?
Yeah the position/velocity of the rigidbody,
Well it depends on a few things
- Do you have interpolation or extrapolation enabled on the body
I believe if you have interpolation on then yes the position may change between Update and LateUpdate
if you don't have interpolation on, then the Rigidbody position will only change during the physics simulation which is after FixedUpdate and before Update
It seems I will want to use FixedUpdate instead of Update
also note that Rigidbody.position and Transform.position can be different, especially with interpolation
Generally for physics, yes, you should use FixedUpdate and Rigidbody.position not Transform.position
Ok well my solution isn't working so well so here is what I am trying to do.
My characters are squares. Imagine square A and square B.
When A jumps on B, I want it so that when B moves, A also moves (like there is 100% friction).
I would use 100% friction except that would also mean when A moves, B also moves, which I dont want
I think the problem with FixedUpdate was that it didn't look smooth since it gets called less frequently than Update (sometimes)
you want a platform
wdym
It sounds like you're taking about like having moving platforms for the character to jump on
I'm asking a question
not making a suggestion
"a platform" doesn't really mean anything specific
Any better than average state machine tutorials out there? Most of the ones I've been able to fine seem ghetto and have let me down.
Its kind of like Pico Park mechanic, if you every played it
Tutorials for something like a state machine tend to have over-engineered solutions. It really depends on what you're trying to accomplish with this thing.
Like rn the characters can jump on each other, but since there is no friction, when the lower character moves, the upper character does not move with it
Real. I know I shouldn't but I'm very tempted to make it a small scale one where I just keep everything within script. States are regular movement, a dash, wall run, brake, and a slam. Maybe like two more if I feel like it.
Every day I learn there are a lot of tutorials out there that do more harm than good when you try to build on them. ;-;
ive looked at the code some more, i found out that it was because of a static list instead of a regular list lol, but thanks to everyone who helped
Can someone explain why my muzzleflash is not aligned properly with the gun even though in the scene view, that doesnt seem to be the case
Rotate the camera in the scene view. Look at it from more than one angle
that wasnt the issue, I fixed it, basically I am using two cameras to render then gun and the rest seperately. The reason for the misalignment was that the layer of the muzzleflash and the gun werent the same. Making them the same layer fixed my issue
crap'ola I copied pasted copy pasted saved and cant undo, got a funni format now
tried paste plain text and paste back in from notepad.exe already using UTF-8
I tried googling, sorry if this question is just plain odd
Is your problem something like this? https://stackoverflow.com/a/4065828/1132437
Oof unfortunately no, but I manually removed them for now 🧹 haha maybe it won't happen again
thank you though
can someone send the tutorial thing on how to get code to autocomplete
!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
screenshot external tools in unity preferences
sometimes takes a bit for to load up
I now know OnDestroy and OnDisable are not the same 🙂
What is UTF-8?
Hey everyone, I am wondering if someone can give me some keywords to search for or straight up links to something that will help me acheive the following:
I want to create code that will help me simulate millions of games of a "connect-4-like" game to find out either; what the next best move is by weight, or just simply giving me statistics on who is more likely to win just by playing first.. etc.
any help is greatly appreciated... except a link to a connect-4 neuralnetwork github lmao. I'm trying to apply knowledge to my own game... connect-4 just closely resembles it. thanks!
Hey so I have this script for having an enemy turn to face the player via animations which turn it to face a specific angle. But when I want to to take its new angle into account when deciding how far to turn again it just wont work. When I have the current transform - rotation that faces the enemy it's a negative, and when I have the rotation towards the enemy - the current rotation than it gives me a completely different current rotation despite me not touching anything besides the transform.rotation.y - lookrot.y part.
Might be worthwhile to learn how Stockfish works: https://blogs.cornell.edu/info2040/2022/09/30/game-theory-how-stockfish-mastered-chess/
that's for chess not connect 4, but it should be applicable to any game.
using euler angles that come back from a Transform, especially a single one in isolation is always a recipe for disaster
euler angles are not unique, as you are seeing
And there's no telling which of the many valid combinations of euler angles the Transform will give you back for any given rotation.
What are you trying to achieve exactly?
I have this animation tree which turns a given amount of degrees. I'm trying to get the amount of degrees between the enemy's current rotation and the rotation which faces the enemy that need to be fed into this in order to turn.
I guess you could just contextualize it as getting the amount I would need to transform.Rotate between the current point and the one I need to face
your best bet is probably to use this https://docs.unity3d.com/ScriptReference/Vector3.SignedAngle.html (you can add 360 to the result for negative results to convert [-180, 180] to [0, 360])
Ok I'll try that out
I want to be able to treat the characters as moving platforms.
Ok so I have it when character A jumps on character B, A.transform.parent becomes B.transform. Yet whenever B moves, A doesn't move. I have read it might be because I am using RigidBody2D with dynamic body type, but I have seen tutorials where it worked.
Is it because both A and B are dynamic, and B (the moving platform in this case), should be kinematic?
Just playing with parenting and rigidbody body types won't get you the effect you need
is their code open source? do you know how many lines of code stockfish is? how could i start building something like this?
Yes stockfish is open source https://github.com/official-stockfish/Stockfish
I got a quesiton about lifecycle..
my GameObject instance is seemingly reinstantiated on a domain reload but neither Awake nor OnEnabled fire.. do I really have to catch OnAfterDomainReload statically and then roll that over on the instances by hand?
or should I just do all my initialization in the ctor?
What's the end goal here?
What is this causing an issue with
I got some variables that come up null after the domain reload and I want to have it consistent.. I would want to reload the parts that need reloading but I'm thinking now.. if the object is completely reinstantiated I best just initialize everything fresh in the ctor
It worked great with a bit of fiddling, thank!
I'm using a raycast to determine LoS between non-player entities. I'm a bit lost on finding anything but the target's center. Is there a way to work out the profile of a hit entity? (from there I could ray cast the left-most point, right-most, etc and get everything I need).
One option is to make empty GameObjects at the extremes of the object, and use those as the raycast targets
maybe like 4-5 representative points for example
Oooh I like that idea more than my fallback option, which was scanning a wave until a cast missed.
Another option is to use the Renderer bounds and use https://docs.unity3d.com/ScriptReference/Bounds.IntersectRay.html to raycast to it
that's not going to be incredibly accurate depending on the shape of the object though
the accuracy isn't a huge concern, as long it's not heading into jank territory. The main issue I want to overcome is where a unit may be partially viable behind something (say, terrain) but the ray cast will intersect the obstruction when looking at the center.
The more I think about it, the more I think the empty objects is the go. They detect each other via colliders, so instead of firing 1 ray cast at the entity (defaulting to center), I can loop the empty objects until I see one.
Thank you!
ok, so I got a couple member variables and I would set all this up in the ctor but MonoBehaviour can't have a ctor
UnityException: GetComponentFastPath is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'DO_Planet' on game object 'Planet'.
See "Script Serialization" page in the Unity Manual for further details.
UnityEngine.Component.GetComponentFastPath (System.Type type, System.IntPtr oneFurtherThanResultValue) (at <91ab5f1018a44edcbcbbe289ed4303bc>:0)
UnityEngine.Component.GetComponent[T] () (at <91ab5f1018a44edcbcbbe289ed4303bc>:0)
DO_Planet..ctor () (at Assets/_Scripts/Planet/DO_Planet.cs:62)
so what's the best way to initialize lifecycle wise.. needs to be availble after domain reload. Start, Awake, OnEnable are not called
needs to be availble after domain reload
What do you mean by this? What are these variables used for? Is this an editor scripting thing?
mostly editor scripting, yes
You can always just use a property
and lazy load it
private Planet _planet;
public Planet Planet {
get {
if (_planet == null) _planet = GetComponent<Planet>();
return _planet;
}
}```
I want to do initialization logic on this object though and I need the components
meh :|
you're saying you need initialization logic and all this stuff - and it's for an editor tool or something
seems like fields on a MonoBehavuour might be the wrong tool for it
It's not clear why your values are being reset if they're normal serialized fields
that's not supposed to happen
so something weird is going on here
I just want to make sure the object is ready when I call things on it from my editor tool.. it's weird to me the object is being reinstantiated but there is no lifecycle hook and I can't use the constructor
have you editor tool call an Initialize function
My guess is you're using nonserialized fields or something
which yes, will go away on a domain reload.
this is not an issue to me.. I just want to reload it when the domain is being reloaded and I'm wondering what's the right lifecycle hook, there HAS to be one, no?
marking the fields as [SerializeField] helped but now my issue is, I serialize a dictionary by hand:
[SerializeField]
private Dictionary<int, DO_Planet_Biome> _biomeTriangles;
//---
string json = JsonUtility.ToJson(_biomeTriangles, true);
the dictionary is definitely not empty but the json comes out {}
any idea why?
unity cannot serialize dictionaries
I see, thanks
Don't use JsonUtility, use Newtonsoft
JsonUtility can't serialize/deserialize common types
But even then, Unity can't show your dictionary in the inspector; you probably need to create a custom editor for it
or grab a serializable dictionary off the shelf
any reason not to suggest System.Text.Json?
It's not included in Unity by default and there are simply better tools available
stj is the best json serializer, so that's not true. can unity not include nuget packages?
What makes it the "best" serializer in your opinion?
And no, Unity cannot use nuget packages out of the box
What are you basing that on?
like every source online. it's also fairly easy to benchmark yourself
but not really important if you can't use it anyway 
I can't find any source that compares Unity's JsonUtility with System Text Json
possibly because a comparison isn't easily possible
i would be very surprised if JsonUtility was anywhere near stj
JsonUtility is pretty feature limited, and focused on speed
stj is made by the greatest minds at dotnet, it only makes sense that they know how to eek out every cpu cycle they can :p
I wouldn't be surprised if it beats Newtonsoft
STJ is a pain in the ass to get working with Unity, no point in suggesting it to beginners
And Newtonsoft has an easy to use library for Unity
using newtonsoft now, thanks guys
@wintry quarry So these are the two scripts:
Script 1: A Script designed to re-order bones of a SkinnedMeshRenderer to match another SkinnedMeshRenderer's bone order (using the root bone)
Script 2: A script that "Creates a new mesh based off the bone structure of a base mesh and ensures everything is in the correct order in the new mesh."
So my issue is that the second script works, but the results aren't as good as the first, as it does attach the new mesh to the bone order of whatever you are trying to mimmick, but does so with a lot of cavieats. One problem is that if the bone locations are even slightly off, the area where bones rotate around, will appear to be outside of the model, causing the rig to break. The first script is really good, looks the best, but does so by having a separate SkinnedMeshRenderer, and I want to end up with the ability to seamlesly switch the mesh in the SkinnedMeshRenderer without the bones breaking (if that makes any sense. Basically, combining the quality of the first script, with the end result of a seperate new mesh of the second.)
The second script does take into account the "bind pose" so I'm looking into that, but it's honestly so over my head all of this
Is there a way to make this (a unity scene file) show up in editor?
public Scene _scene;
I basically want to link a scene to a background music file. I could use the build index ofc, but just curious how to make the field show up in my inspector. 🙂
I don't think scenes are serializable, are they?
Unless this changed in the past few years. it didn't when I used it
Asked chatGPT and it says its not possible
You can always make a custom editor
They are not. It's Run-time data structure as the documentation tells
ChatGPT would only know up until 2021, which is plenty of time for it to change
true
You can find assets online for doing just that though
If it doesn't work, this post has an example on writing a custom inspector https://discussions.unity.com/t/inspector-field-for-scene-asset/40763
I can't verify it (still) works. I suggest you try making your own from this reference
You may always ask on #↕️┃editor-extensions if you need help with your editor scripts
It's shame the Scene assets are made so they cannot be easily referenced. I bet almost all larger Unity dev companies have made their own scene management tools to easily reference and manage their scenes
I would not be surprised if there are readily available libraries that allow you to see Scenes and Dictionaries and all that in the inspector
Perhaps they haven't done it because it's opinionated, but it's not the only missing thing that you'd expect to just work
Why does this show an Error at Random? Before pasting in the Instantiate code above it worked just fine
I posted about this yesterday with no real luck so I'm posting again this morning.
Im having this strange issue where when I'm trying to reflect projectiles off of a wall, they reflect off the inner portion of the collider, as seen in the photo. The green trail is the projectiles movement, the red debug raycast is the raycast seen below. I also checked the normal/hit position and debugged that, where it shows that it is inside of the collider at the normal you'd exepct to see in that photo. (Tho not the expected results.)
Any ideas?
RaycastHit hit;
if (Physics.Raycast(transform.position - transform.forward, transform.forward, out hit, 10f, Utils.GetCollisionMatrixLayerMask(gameObject.layer))) {
Vector3 hitNormal = hit.normal;
Debug.Log(hit.collider.gameObject.name);
Vector3 bounceDirection = Vector3.Reflect(rb.velocity, hitNormal);
rb.velocity = bounceDirection;
Debug.Log("Bouncing");
return;
}
Where the util is
public static LayerMask GetCollisionMatrixLayerMask(int layer) {
LayerMask collisionMask = new LayerMask();
for (int i = 0; i < 32; i++) {
if (!Physics.GetIgnoreLayerCollision(layer, i)) {
collisionMask |= (1 << i);
}
}
return collisionMask;
}
Likely you are having ambiguity between System.Random and UnityEngine.Random. Make sure to include the error message in your question if you encounter one
Yeah thats it, since error messages seem so specific its hard to translate them correctly without misspelling a word since mine are in German. Does the Error code work too for the future?
both preferred, even if german
I took out using System; would this break anything significant? Because it works now
if you're not using it, then you don't need it
Thanks alot!
Sometimes you will need both namespaces, so you can specify which one to use by writing System.Random.Next() for example
Or use a using statement like a sane person
using UnityRandom = UnityEngine.Random;
...
code
{
_ = UnityRandom.Next();
}
What a smooth little trick! [noted]
this has been bugging me for a while, sometimes I try to reference anything inside Unity or System or any of the essentials, and vs 2022 acts as if it's not there. Restarting fixes it, but is there any other solution to this?
You need to 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
Regenerate project files should help
no, it works fine, but it sometimes does this weird error. Restarting makes it go back to normal, so I don't think it's an IDE issue?
Also make sure your IDE package in Unity is up to date
alright, will do. Thanks.
lol hi I still don't know what to um check for
then re-read that message
how are the normal and velocity inputs?
because those are the values you input to Vector2.Reflect. i'm not saying they are input from the player
now you should be able to see why the Vector2.Reflect is behaving the way it has been. then i get to link you to a message from 3 days ago that also explains it
Is there any context with these two errors?:
Assets\FoundationalRealm\PlayerCharacterController\Scripts\PlayerCharacterLocomotionInput.cs(7,66): error CS0535: 'PlayerCharacterLocomotionInput' does not implement interface member 'PlayerControls.IPlayerCharacterLocomotionMapActions.OnMovement(InputAction.CallbackContext)'```
Especially as I followed excatly as the video is setup for `IPlayerLocomotionMapActions` in this video: https://youtu.be/muAzcpAg3lg?si=M3Jfn-y6fCX-2zNe&t=766
```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace FoundationalRealm.PlayerCharacterController
{
public class PlayerCharacterLocomotionInput : MonoBehaviour, PlayerControls.IPlayerCharacterLocomotionMapActions
{
public void OnMovement(InputAction.CallbackContext context)
{
throw new System.NotImplementedException();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
}
In this series, I'll be going over beginner through advanced topics for building a complete player controller, both for 1st and 3rd person. We'll covers topics like movement, jumping, slopes, wall handling, step handling, animation, blend trees, Mecanim, Cinemachine, avatar masks, animation layers and multiplayer.
This is a free complete course...
did you actually bother reading your log messages?
so which of the relevant values do you think is not what you expect it to be?
reflected velocity
are you missing a using directive?
make sure your !IDE is configured so that you can use the quick actions to add the relevant using directive
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
please engage your brain and try again
cause if it was reflected wouldnt the value just be the inputed velocity with one of the components multiplied by -1..
we obviously know that the reflected velocity is wrong. that is literally the entire fucking issue. you are trying to determine why it is wrong.
chill ok
Both IDE are configured.
you've been at this for 3 days, and you've printed the relevant values but still somehow haven't noticed that your actual velocity before reflecting is practically 0. for the love of god think
well for starters that first one should be uninstalled. but that's also not the only configuration step
Removed VS Code Editor
Lemme check if I miss something
fair enough
okay and have you completed all of the other steps for configuring whatever IDE you are using?
i thought the x and y were coordinates for the initial impact
I'm making sure I did.
Updating right now
anyway, now that you finally have realized that the velocity is 0, you instead need to store the velocity after each time you change it and use that to reflect rather than the current velocity. because the rigidbody's current velocity has already been affected by the collision in OnCollisionEnter2D
Good news, I fixed the issue. Turns out I did miss a bunch of steps along the way. Thanks @slender nymph.
My tag isn't changing again. Here's the code: https://pastecode.io/s/gpebz2c5
Log the tag of the other object before any evaluation
I did.
Where?
I removed it
Log the tag of the other object before any evaluation and show us what the console printed
IDK how to do that
How to log or how to show us the console prints?
Both
How do you say you don't know, after saying "I did" #💻┃code-beginner message
For the first, just undo what you said you did here #💻┃code-beginner message
For the second, you would just screen capture the Unity console window
Everytime i tap on the screen a prefab "point" spawns for a few seconds to simulate touch on the mobile device, and then immediately destroys itself again.
Whenever another certain prefab is triggered by this point(by using collision), it is destroyed and i get added 1 point.
However i also want to make it so that when the background is accidently tapped, the console debugs: "FAILED" so i know it works and the player loses for missing the prefab.
This works, but whenever i tap the prefab, it both gives +1 point aswell as it debugs "FAILED" over and over again. As if it detects both the prefab and the background at the same time.
i tried changing the layer order but it still doesent work.
How can i make it in a 2D game, that a OnTriggerEnter2D of one object only applies to the next higher gameobject in a layer and not to those below it?
using UnityEngine;
public class spawner : MonoBehaviour
{
public float maxTime = 1;
public float timer = 0;
public GameObject pipe;
public float height;
void Start()
{
GameObject newpipe = Instantiate(pipe);
newpipe.transform.position = transform.position + new Vector3(0,Random.Range(-height,height),0);
}
void Update()
{
if (timer>maxTime){
GameObject newpipe = Instantiate(pipe);
newpipe.transform.position = transform.position + new Vector3(0, Random.Range(-height, height), 0);
Debug.Log(newpipe.transform.position);
Destroy(newpipe, 15);
timer = 0;
}
timer += Time.deltaTime;
}
}
``` Gues, I writing simple flappybird game. Why this code to spawn and moving pipe not wirking??
is there any special reason for spawning this point prefab at every touch? why not use IPointerClickHandler.OnPointerClick?
I was checking out touch input variants but it was very complex and dit not work well so i thought to one day take a look at it again, what does this do exactly?
Show the inspector of the object this script is on
you implement this interface on the desired object and it's going to be called whenever it receives a click, so I think you won't need to care about filtering the layers or anything like that
you probably can also use the MonoBehaviour event OnMouseDown
Does the click matter, so has it to be a mouse click or does it work like a button where any input regarded as a "press" works?
pretty sure it reacts to mouse clicks and touches
Thanks alot!
I have this
As the game plays, do you see the timer variable increasing? Are you getting your log statements when a pipe is spawned?
I have a question that I think I know the answer to. If I am creating games and I reuse my previous code for the new stuff. Is that wrong? I am thinking like player controllers, scoring systems, timers, and anything else that can get reused. My knee jerk answer is this is fine and kind of how it should be done. Don't reinvent the wheel every time. I can also see where this might be a crutch that holds you back from progressing in your skills. Thoughts?
there is no reason to reinvent the wheel every time you create a new project. reuse code when you can if it makes sense to