#💻┃code-beginner
1 messages · Page 508 of 1
use the {}
where would i use {}
I have a collider on the object
an object after you declare it
yo boxfriend, you want the smoke?
you can take your shitposting somewhere else. i told you what you need to use, so put literally any amount of effort in by googling it
this answers pretty much none of what i asked
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers
feeling generous 🙂
The rigidbody isn't kinematic and the acceleration is set to 10
- did you verify script is running ?
- did you debug your direction + speed combined value
eg```cs
var wishDir = car.forward * vertical * Acceleration;
rb.AddForce(wishDir, ForceMode.Acceleration);
Debug.Log(wishDir);//
Debug.DrawRay(car.position, wishDir); //or this mayb
The debug prints values but the car still wont move
show the inspector for this object
don't need to crop show it selected in the scene
select it in Local mode
make sure forward is not like down or some shit lol
might be too much mass and too low acceleration / force
Forward stays ths same in local
also make sure that your acceleration is high enough to overcome friction
ya crank that
Im so stupid
// If the inventory this cell is has a weight limit and can still fit something in
if(cell.inventory != null && cell.inventory.maxWeight != 0)
{
Debug.Log("Item Amount: " + item.amount);
Debug.Log("Item Weight: " + item.itemData.weight * item.amount);
Debug.Log("Max Inventory Weight: " + cell.inventory.maxWeight);
Debug.Log("Inventory Weight After Adding: " + (cell.inventory.currentWeight + (item.itemData.weight * item.amount)));
// The current weight is above the max weight or if this item was added it would exceed the limit
if(cell.inventory.currentWeight > cell.inventory.maxWeight || (cell.inventory.currentWeight + (item.itemData.weight * item.amount)) > cell.inventory.maxWeight)
{
Debug.Log("No i don't feel like working today");
return false;
}
}```
this literally makes no sense
it literally checks if its above
and somehow its still false
even tho currentWeight isnt above maxWeight
you should format those numbers to include more digits because i bet it is above maxWeight due to floating point imprecision or something
Does anyone know a playlist that will help me make a gacha game
in that case format your code better so you don't have giant strings of calculations being repeated by utilizing local variables, it will also make debugging easier.
brother
I saw one on it but I think the creator deleted it
why is it red shaded btw
i changed the play mode color
what do you mean by playlist
to make it more clear when in play mode
On YouTube
things only get messy when theres multiple items
if the item.amount is more than 1
if its 1 then it works fine
mate, your code is practically unreadable because of the amount of objects you are accessing per line. if you don't want to format your code to actually be readable then i won't help you
it's literally as simple as just using some local variables. var newTotal = cell.inventory.currentWeight + (item.itemData.weight * item.amount); then you just use newTotal in place of all of the instances where you are doing that calculation again
i know but i only started working on this a few minutes ago
so i couldnt be asked
i do that at the end
i'll change it hold on
// If this cell uses a specific inventory and has a weight limit set
if(cell.inventory != null && cell.inventory.maxWeight != 0)
{
var inventory = cell.inventory;
var itemWeight = item.itemData.weight * item.amount;
// The current weight is already above its max weight or if you added the item weight to the current weight and it would be bigger than the max weight
if(inventory.currentWeight > inventory.maxWeight || (inventory.currentWeight + itemWeight) > inventory.maxWeight)
{
return false;
}
}```
that should be more readable
the first if check isnt the issue
its the second one
i just added this debug
let me check
what
once again you are copy/pasting calculations because you didn't bother putting them into local variables. do that and then you can easily print all of the relevant values at the same time
whats your axweight
my what
maxweight
for example, if you stored inventory.currentWeight + itemWeight in a variable called newWeight you could print this: Debug.Log($"Current Weight: {inventory.currentWeight}, Max Weight {inventory.maxWeight}, add item with weight {itemWeight} would be {newWeight}.");
If you're having this much trouble just logging out variables use the debugger and just inspect the variables and outcomes directly
-9 isnt a strange outcome. I dont know how much you added but we checked if currentWeight is bigger than max so it should be in -'s
alright
explain to me
difference between these two
because the top one works
even this works
its this bit (cell.inventory.currentWeight + itemWeight)
why did you add item.itemData.Weight * itemAmount to current weight? doesnt it already have them
because multiple items
for each item u add weight
still i dont understand why (cell.inventory.currentWeight + itemWeight) works but (cell.inventory.currentWeight + (item.itemData.weight * item.amount)) doesnt
its the same thing, i wrapped it in the brackets
you have an error in the console that you are ignoring
how did you know
because i know how loops work lmao
@slender nymph is that because of floating point precision thing?
possibly 🤷♂️ inspect the actual values using the debugger to find out
i mean it works
can you add multiple items at one time
wdym
yeah
u can drag multiple items into cells
Beacuse you have no way for your while loop to end?
So it's infinitely running in a single frame, not allowing your game to progress.
Does your log actually print though?
no
If you comment it out, does it still freeze?
when i ran it the code just kept running without being able to stop it
i dont understand
The loop, if you remove it, does your game still freeze?
no it works fine if i remove it
i thought that the while loop would end after runningTotal got bigger than whatever maximum i put in the condition
Yes, in theory that should work
But also not needed. It'll run in a single frame, you could essentially set the value manually and it'll do the same thing.
im looking to get a series of numbers using the calulation for runningTotal
now that im thinking about it a for loop would work better but I want to understand why this loop didnt work
why is it an infinate loop
just got it working
the problem was I was using '=' instead of "+="
thank you
Ah yes, sorry, I'm playing games so I was skimming the code
I've got a bunch of ui elements on my screenspace-camera canvas
and I want to connect all of them up with line renderers
but I'm getting stuck on how to turn their position into something usable for a line renderer
Playing games instead of helping full time tch tch 😆
Their positions can be used as points for the line renderer directly! Just make sure the LR uses global space
interesting
straight up UI_element.transform.position can be thrown into the line renderer and it just works? kinda crazy
Or maybe you need to do Camera.main.ScreenToWorldPoint lol.
ok both transform.position and screentoworldpoint give me craaaazy numbers that don't match up with anything
ui position is tricky stuff
yeah doing transform.position on these things is not doing me so hot
get the position from rectTransform
the issue I'm having is incredibly weird. after a lil investigation it kinda looks like the transform.position of the ui elements is incorrect for the first frame and then correct afterward
I have a debug.log in update() writing down the transform.position of one particular ui element.
for whatever reason, the first 2 frames has an incorrect position, but then the third frame and then on is correct
which is even weirder given that there is zero other code anywhere that moves the UI elements after start(), yet they're moving during update() before resting to their final position
Can anyone help me figure out why nothing is outputted to my Debug Log here:
anyone got any idea how to fix this code so there isnt a break inbetween the clips playing?
using System.Collections;
public class MusicLooper : MonoBehaviour
{
public AudioClip firstClip; // First audio clip to play once
public AudioClip secondClip; // Second audio clip to loop
private AudioSource audioSource;
void Start()
{
// Get the AudioSource component attached to this GameObject
audioSource = GetComponent<AudioSource>();
PlayFirstClip(); // Start playing the first clip
}
private void PlayFirstClip()
{
// Set the first audio clip and play it
audioSource.clip = firstClip;
audioSource.Play();
// Schedule the second clip to play right after the first clip ends
Invoke(nameof(PlaySecondClip), firstClip.length);
}
private void PlaySecondClip()
{
// Prepare to play the second clip in a loop
audioSource.clip = secondClip;
audioSource.loop = true; // Set to loop
audioSource.Play(); // Play the second clip immediately
}
private void OnDisable()
{
// Stop the audio when the object is disabled
audioSource.Stop();
}
}
!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.
do you have a EventSystem in the scene
Yes
thanks
idk if your the same guy from yesterday? because its the same issue
but if your not, you can try subtracting a small amount like 0.01f from the clip length
im not, and i tried that and it didnt work
will you only have 2 clips always?
try logging the time when you invoke and when it plays and see if its the same or not
iw ill only have 2 clips, so i'll try that
I'm trying to create a random vector and apply it to a game object but the code wont work
wont work how
is there an error?
Assets\ballScript.cs(10,30): error CS1955: Non-invocable member 'Vector3' cannot be used like a method.
Assets\ballScript.cs(10,51): error CS0236: A field initializer cannot reference the non-static field, method, or property 'ballScript.minPosition'
Assets\ballScript.cs(10,66): error CS0236: A field initializer cannot reference the non-static field, method, or property 'ballScript.maxPosition'
Assets\ballScript.cs(10,95): error CS0236: A field initializer cannot reference the non-static field, method, or property 'ballScript.minPosition'
Assets\ballScript.cs(10,110): error CS0236: A field initializer cannot reference the non-static field, method, or property 'ballScript.maxPosition'
Assets\ballScript.cs(10,139): error CS0236: A field initializer cannot reference the non-static field, method, or property 'ballScript.minPosition'
Assets\ballScript.cs(10,154): error CS0236: A field initializer cannot reference the non-static field, method, or property 'ballScript.maxPosition'
Assets\ballScript.cs(19,17): error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)
Assets\ballScript.cs(22,13): error CS0103: The name 'myRigidbody' does not exist in the current context
many errors
Is MyRigidbody an outside class? If not you never defined it in your BallScript class
the last one i understand
ok so the main one is your not using new for your Vector3
timer is an int but it should be a float
It gives me this, hower there is like a second or 2 between the 2nd clip starting
thanks
also it should just be timer += Time.deltaTime;
thank you
i still cant get the middle chunk of errors though
all on that "randomPositon" line
you should be doing that inside a method
not when intializing the variable
make a new method SetRandomPosition() or something, or do it in Start if you do it just once
I keep making that mistake. Let me see if I can solve the last few errors.
good news I was able to resolve my issue
I figured out that it takes several frames for the UI elements in layout groups to update their position after deactivating and activating elements within it.
I was spawning the lines before their new position was found. so I put a coroutine to wait half a second before spawning the lines to give the ui time to update and now it works
nice find! looks good
I think it's a little weird how offset the ui update is, to the point that it takes 2 whole frames of waiting to get the real new position
but whatever, I have a working thingy now.
I've spent 90 minutes on something I thought was gonna take 15
and a working thingy is all we need
it turns out transform.position on a ui element IS the correct world position
no rect handling needed
how do I get my code to ask for a rigidbody2d that I can drag and drop into the script component in the editor?
public Rigidbody2D rb; like this you mean?
or you can do [SerializeField] private instead of public
yes
i think im doing this but its still not asking for the rigidbody
im sending the code
you mean it doesnt show in the inspector the slot?
yes
do you have any errors in the console
yes
then you need to fix them
only one error that says that im not referencing rigidbody
Assets\ballScript.cs(7,12): error CS0246: The type or namespace name 'RigidBody2D' could not be found (are you missing a using directive or an assembly reference?)
ah
because its supposed to be body
not Body
that suggests to me your !ide isnt configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
thanks ive been meaning to do this
My code for teleportation doesn't work half of the time sometimes the screen will visible try to move but then arrive back at the players position
is it a character controler?
'using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerRayCast : MonoBehaviour
{
public float cooldownE = 10f;
public int energyQ = 60;
public float cooldown = 0f;
public string debug;
Ray ray;
RaycastHit raycastHit;
Vector3 RayPosition;
void Update()
{
cooldown -= Time.deltaTime;
ray = new Ray(transform.position, transform.forward);
Debug.DrawRay(transform.position, transform.forward, Color.white);
if (Physics.Raycast(ray, out raycastHit))
{
if ((Input.GetKeyDown(KeyCode.E)) && cooldown <= 0.0f )
{
if (raycastHit.transform.tag == "wall")
{
transform.position = raycastHit.point;
cooldown = cooldownE;
Debug.Log(transform.position);
}
}
}else
{
if ((Input.GetKeyDown(KeyCode.E)) && cooldown <= 0.0f )
{
transform.position += transform.forward * 5;
cooldown = cooldownE;
Debug.Log(transform.position);
}
}
}
}'
Yeah
So I have to disable all character movement and then teleport
is there a way to disable scripts for a short time?
scriptReference.enabled = false;
characterController.transform.position = newPostion;
scriptReference.enabled = true;
u can do it all in the same frame..
Alright thanks
I keep getting the an error that says that "randomPosition" doesnt exist in the current context on line 23
how do i call the randomPosition variable correctly
i think on line 14 you are caching a new local variable instead of assigning it to the defined field at the top line 11
if you remove Vector3 from line 14 and assign the random position directly, it should work.
thank you
you're welcome!
if i (by mistake) change and save code while the game is running, several times :/, can this corrupt things? i just has the worst three hours until i just copied the exact same code into the file i had been working on
you might have to ask #🖱️┃input-system
oh got it thanks!
I am about to setup a local git for my project(s). i wanted to use Gitkraken, because i found a video on how to do it 🙂 problem is, gitkraken is closed source, so i will not be using that.
Anyone know of reasonable GUI alternatives to it? Windows system
Fork is a decent one@near wadi
does anyone know how I can restrict the generated PlayerInput C# class to use only one control scheme
Cool deal, thanks
anyone know where I can learn unity 3d?
I understand nothing that's going on and all the sprites I import are low quality for some reason
Unity !learn as well as the manual
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks so much
Mornin' all, I'm having a weird issue that I can't seem to find the cause of.
Simple spaceship controller......
https://hastebin.com/share/arahisapis.csharp
When I enable the controller script, the ship moves by itself (really small amount, but it'll 'build up' until it gets to a point where it will break the game)
Video for reference.
https://streamable.com/5z0ubr
Can anybody see what the issue might be in the script please?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
um the variables dont show up in inspector, anyone got solutions? :\
Properties dont get serialized. You can tell unity to serialize the backing field with [field:SerializeField]
oh it worked, thanks so much!
i tried to make a 2d movement in right and left direction with the new unity input system. the keybind are wasd. i noticed that everytime i move and pressed w / d, my movement are slower because the value got split in half. ( example : normal value 1, becomes 0.71 ). it becomes slower because i multiply it by player speed. Can someone help me to make value doesnt get split in half?
Normal Vector2 value condition : Move Value = (0.00, 1.00)
Half Vector2 value condition : Move Value = (-0.71, 0.71)
public void OnMovementInput(InputAction.CallbackContext context){
MoveValue = context.ReadValue<Vector2>();
Debug.Log("Move Value = " + MoveValue);
}
don't normalize the vector
i tried to normalize it because i thought it would work, but its not
do you know what normalize does?
makes value to 1?
no, makes magnitude = 1
What doesn't work?
my movement still are slower when i pressed up / down
Don't normalize it.
i dont
What's the issue then?
I'm assuming you're working with the raw values now or something. Not a whole lot of info was shown.
i wanted to make the movement speed the same even when player pressed up / down keybind. and what's make my movement speed slower is because when ReadValue notice of 2 direction input. they will split half the value, idk why and thats what i want to fix
the normalize was what was causing the 1 to become 0.71 so where is the problem now?
is not
The value is not split in half, it's normalized - the 0.71
Half would be 0.5
If you want the values to be one or zero: divide by the value and multiply by one - cast to int if you aren't wanting floating point values ect or some math function (divide by zero warning)
Or round round up to one etc
Check the mathf class for Unity
Could probably floor each value https://docs.unity3d.com/ScriptReference/Mathf.Floor.html
actually im just gonna ask at #🖱️┃input-system
I have a singleton managing the day night cycle in my game and I want it to send out a signal or something whenever it goes from one day to another so that the 100s of objects that use that data can evaluate only when the day changes
My current solution is each of them checking if the day has changed in the fixed update function
But I’m scared about it’s scalability
get the objects to subscribe to an event, then fire the event when the change happens
help me why this no print
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class HeatButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public bool buttonPressed;
void Update()
{
if (buttonPressed)
{
Debug.Log("Button is pressed");
}
}
void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
{
Debug.Log("Pointer Down");
buttonPressed = true;
}
void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
{
Debug.Log("Pointer Up");
buttonPressed = false;
}
}
wot no print
do you have a GraphicsRaycaster in your scene
i dont i only have a event sytem
then I suggest you go and read the docs on the IPointer interfaces
alr
Can anyone help me fix my teleportation code
using System.Collections.Generic;
using UnityEngine;
public class PlayerRayCast : MonoBehaviour
{
public float cooldownE = 10f;
public int energyQ = 60;
public float cooldown = 0f;
public string debug;
Ray ray;
RaycastHit raycastHit;
Vector3 RayPosition;
void Update()
{
cooldown -= Time.deltaTime;
ray = new Ray(transform.position, transform.forward);
Debug.DrawRay(transform.position, transform.forward, Color.white);
if (Physics.Raycast(ray, out raycastHit))
{
if ((Input.GetKeyDown(KeyCode.E)) && cooldown <= 0.0f )
{
if (raycastHit.transform.tag == "wall")
{
GetComponent<PlayerCode>().enabled = false;
transform.position = raycastHit.point;
cooldown = cooldownE;
GetComponent<PlayerCode>().enabled = true;
}
}
}else
{
if ((Input.GetKeyDown(KeyCode.E)) && cooldown <= 0.0f )
{
GetComponent<PlayerCode>().enabled = false;
transform.position += transform.forward * 5;
cooldown = cooldownE;
GetComponent<PlayerCode>().enabled = true;
}
}
}
}
It sometimes doesn't teleport you
start by debugging it
And sometimes blinks teleport so it just blinks but doesn't teleport
Its supposed to teleport you in the direction your facing and the raycast is so you don't clip into objects
Do all your walls have the wall tag?
Yes
What's playercode supposed to be?
Basic movement code and camera
more to the point, why are there 4 GetComponents on it in Update?
To disable the playercode then enable it again
that does not explain why there are 4 of them in Update
Are you using a rigidbody or character controller?
no rigid body
just character controller
if you have CharacterController why use transform.position?
I'm pretty sure that there's code in PlayerCode that could be teleporting you back.
But more to the point, do cache the reference to PlayerCode rather than calling getcomponent so frequently.
It's possible that you teleported into a wall, and because charactercontroller doesn't know where to bring you to, so it teleports you back to your last position instead
So how do I fix this?
Does PlayerCode inherit from CharacterController?
I think
do you know what inheritance means
Yeah one object inherets a behaviour from another
or am I wrong?
In your code you see something like public class PlayerRayCast : Monobehaviour, PlayerRayCast inherits from Monobehaviour
What does PlayerCode inherit from?
MonoBehaviour
[RequireComponent(typeof(CharacterController))]
Also there's this
Not PlayerCode
That's not exactly related tbh
Oh ok
CharacterController has a thing where if you try to change the players position, it will teleport the player back.
That's why we disable the CharacterController before teleporting the player, then enabling it again afterwards.
I'm not sure what disabling PlayerCode does for you, but you should be disabling CharacterController instead
Alright thanks a lot for the help
It's just this:
public void VeranderCamera(int optie)
{
cameraController.enabled = optie == 1;
WASDMovement.enabled = optie == 1;
orthographicCameraController.enabled = optie == 0;
Camera.main.orthographic = optie == 0;
}
nothing obviousley strange there, maybe add a Debug.Log to see if it's being called
You can also declare the parameter as a bool instead of an int to simplify that code
Why does my character always fall through despite having a box collider on the grid and the player
not enough info, see #854851968446365696 for what to include when asking for help
Can I? It's the dynamic value from a dropdown
that code on its own wouldn't cause a freeze. something else is causing it. connect the debugger and break all when it freezes so you can inspect what the main thread is doing
hmhm I just created another camera object and switched between these two and now it's fixed
well that tells you it's likely some code on the one that causes it to freeze
it not really a lag freeze, just that I cant click anything/the UI doesn't update
you can't say "freeze" when you mean "everything still works except for UI"
well in that part I was in UI so I couldn't tell the difference easily
Is anyone able to help me please. I have visual studio installed, I have the unity tools installed. I have created a script in unity, automatically opened it in Visual Studio. I don't get any syntax highlighting. I have gone to edit, preferences, external tools, regenerate project files, then reopened visual studio script, still no syntax highlighting. I am using unity 2022 v3.48f1 , and Visual Studio 2022
screenshot your entire visual studio window with the solution explorer visible
hi I'm trying to add a property to my animation but its on read only i tried doing cntl d but it still the same how do i remove read only
this is a code channel. try #🏃┃animation
k ty
aah I see incompatible
this shows that something you have selected is not installed, are you sure you've installed the game development with unity workload already?
I mean, I'm not sure I can make the tick next to the Game development with Unity any more... tickier :p
just ticking the box doesn't install it. you have to actually click the install button
okay well again, something you have ticked is not installed which is why i brought this up
Hi is anyone available right now im trying to implement a drone swarm simulation on unity but im not really sure on how to do it since i have never used unity
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
for now im trying to visualize the drones on unity but im not sure how to put the two together
what version of the visual studio editor package do you have installed in unity
that does not answer the question i asked
and you have completely closed visual studio and restarted it after having regenerated project files?
I've closed visual studio, regenerated project files, reopened, deleted the scripts, closed visual studio and unity, reopened unity, regenerated the script again, reopened visual studio. closed it again, checked that the Unity workload is 'really' installed... 🥲
right click the project in visual studio and select Reload With Dependencies
anyone have any experience in doing simple simulations in unity
oh sorry
Hey, why does my array not have a sort method, is it because it's not an array of a primitive? If so how can I sort it manually?
I want to sort it by smallest sqrMagnitude to biggest sqrMagnitude
Array sort is a static method for the Array object. Array.Sort(positionArray, ...)
oh, thank you
If you use LINQ it'll add methods to arrays
Another question, is the Icomparer just the value which the method sorts by?
or does it do it automatically by the magnitude when taking a Vector3
I don't know if Vector3 has a default comparer implemented. You probably need to pass in your own
Hey guys, I have a question, I'm trying to instance a sprite of a square in the start, but the editor freezes at the moment I start the game, i'm doing something wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RenderBoard : MonoBehaviour
{
private GameObject square;
// Start is called before the first frame update
void Awake(){
square = GameObject.FindWithTag("Square");
//for(int i = 0; i< 10; i++){
for(int j = 0; j<20; j++){
Instantiate(square, new Vector2(2f, (float)j), Quaternion.identity);
}
//}
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
(I only have the square in game)
Do each square have a render board?
what's that?
Your component script
If square has a render board, the Unity Editor will crash on attempting to play
here it is
aaaah I get it, thanks, so maybe move the script to the game manager, right?
I don't think so
not really, no
oh okay i see thanks
and yeah, that was the problem, thank you ^^
Hi i need help i'm trying to make an attack system with a overlapp circle for the range but when i go to the left the circle stays on the right, is there any easy fix ?
hi all i want to ask about this prefab i have already assigned the flock prefab but i still get the error the variable of flock prefab of flockspawner has not been assigned
show that it is actually assigned on the object and not just as a default reference for the script file
hello,
volume slider doesn't attach with this code. do I also have to connect it inside the engine?
public void Music()
{
volumeSlider.value = musicBackground.volume;
volumeSlider.onValueChanged.AddListener(changeVolume);
}
public void changeVolume(float volume)
{
musicBackground.volume = volume;
}```
okay now show what i asked for
which one is that
look at the object you've put this component on and make sure it is assigned there
ohhh alright
wdym by "slider doesn't attach"? all this does is assign the value and add a listener to its value changed event
so when i drag the slider in game, the volume should change right?
assuming that you have actually called the method that adds the listener, and that the volumeSlider and musicBackground variables are assigned
its called in start()
show it
public void StartGame(int difficulty)
{
isGameActive = true;
musicBackground = GetComponent<AudioSource>();
Music();
spawnRate /= difficulty;
StartCoroutine("SpawnTarget");
score = 0;
currentLives = maxLives;
LivesText.text = "Lives: " + currentLives;
UpdateScore(0);
titleScreen.gameObject.SetActive(false);
}
and where do you call StartGame?
wdym? i'm asking where it is called not where you've placed that method in the class. just show the full code
it's not the same as Start . . .
why would you think Start() and StartGame() are the same thing?
Start is a Unity callback function. StartGame is likely a regular function that you'll need to call yourself.
and you have confirmed that is actually being called
public class Difficulty : MonoBehaviour
{
private GameManager gameManager;
public int difficulty;
private Button button;
// Start is called before the first frame update
void Start()
{
gameManager = GameObject.Find("Game Manager").GetComponent<GameManager>();
button = GetComponent<Button>();
button.onClick.AddListener(SetDifficulty);
}
void SetDifficulty()
{
Debug.Log(gameObject.name + " was clicked");
gameManager.StartGame(difficulty);
gameManager.isDead = false;
Debug.Log("is player dead?" + gameManager.isDead);
}
}
i mean the game plays so....
theres no errors
How are you drawing it, show code
I suppose you are drawing it in world space while you need to convert it to local
verify that the methods you expect to be called are being called instead of just assuming
I'm good i found a solution after some time but thanks
do not call that Music method in Update
do you know engines that use python ?
pygame
because you only need to add the listener one time not every single frame
is it very good ?
no, it's crap
damn i see 💀
these are questions you should be asking Google, not us
ur right
okay, i added a start method and called it in there, and now its good
I guess I didn't realize that the start function is it's own thing
He i am working on a small shooter game. And i am now working on the health bar. But the thing is i cant really get it to work. I am getting Confused from my own code.
these are the script for the health system
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
private float speed = 0.5f;
public DamageSystem damageSystem;
void Start()
{
}
void Update()
{
// Move the bullet forward in the direction it is facing
transform.position += transform.forward * speed * Time.deltaTime;
damageSystem.TakeDamage(10);
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("player"))
{
Debug.Log("Hit Player");
Destroy(gameObject);
damageSystem.TakeDamage(10);
}
else if (other.CompareTag("ground"))
{
Debug.Log("hit ground");
Destroy(gameObject);
}
}
}
it is, but if you are actually calling StartGame on the correct object and that the object was referencing the correct slider and audio source then calling Music inside of StartGame like you were would have worked. which is why i told you to verify that you were calling the methods
whats wrong with it
this code alone seems fine
the healthbar doesnt work
how do you make it healthbar? because this code just calls a method
yeah wait sorry, discord has a massages limit
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageSystem : MonoBehaviour
{
public int MaxHealth = 100;
public int currentHealth;
public healthsystem HealthSystem;
// Start is called before the first frame update
void Start()
{
currentHealth = MaxHealth;
HealthSystem.SetMaxHealth(MaxHealth);
}
// Update is called once per frame
void Update()
{
TakeDamage(10);
}
public void TakeDamage(int damage)
{
// Check if current health is greater than zero before applying damage
void OnTriggerEnter(Collider other)
{
currentHealth -= damage; // Reduce current health by damage amount
Debug.Log("Hit Player! Current Health: " + currentHealth);
// Update health system UI or other components
HealthSystem.SetHealth(currentHealth);
// Check if the player is dead
if (currentHealth <= 0)
{
Debug.Log("Player is dead!");
Destroy(gameObject); // Destroy the player object or trigger death logic
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class healthsystem : MonoBehaviour
{
public Slider slider;
public void SetMaxHealth(int health)
{
slider.maxValue = health;
slider.value = health;
}
public void SetHealth(int health)
{
slider.value = health;
}
}
what on earth is that, that OnTriggerEnter should NOT be there
just fix this script
do you know how to fix it?
just remove it completely
it doesnt need to be there, it doesnt make sense to be there
the OnTriggerEnter
in the DamageSystem script?
yeah
also dont call TakeDamage in Update
oh oke
Like this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageSystem : MonoBehaviour
{
public int MaxHealth = 100;
public int currentHealth;
public healthsystem HealthSystem;
// Start is called before the first frame update
void Start()
{
currentHealth = MaxHealth;
HealthSystem.SetMaxHealth(MaxHealth);
}
// Update is called once per frame
void Update()
{
TakeDamage(10);
}
public void TakeDamage(int damage)
{
// Check if current health is greater than zero before applying damage
currentHealth -= damage; // Reduce current health by damage amount
Debug.Log("Hit Player! Current Health: " + currentHealth);
// Update health system UI or other components
HealthSystem.SetHealth(currentHealth);
// Check if the player is dead
if (currentHealth <= 0)
{
Debug.Log("Player is dead!");
Destroy(gameObject); // Destroy the player object or trigger death logic
}
}
}
yeah probably, hard to tell when the code isnt alligned properly with the spaces
test it and see if it works
okay thanks
In the prefab of the bullet when i try to put the damage scriipt in it doesnt get in
you should be getting the damage script from the object you collide with
other.gameObject.GetComponent<DamageSystem>().TakeDamage(10);
at the moment i just shoto a bullet and made it really slow and then hit meself
here is a video
use .mp4, also i already told you what you need to do
here
prefabs cant reference scene objects
oh oki
sorry where do i put?
you put that in your OnTriggerEnter
where you want to take damage
how to you mean. Like the player, or in with script? also like this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
private float speed = 0.5f;
public DamageSystem damageSystem;
void Start()
{
}
void Update()
{
// Move the bullet forward in the direction it is facing
transform.position += transform.forward * speed * Time.deltaTime;
}
void OnTriggerEnter(Collider other)
{
other.gameObject.GetComponent<DamageSystem>().TakeDamage(10);
}
}
i dont know why you removed the Tag checks
but thats how you would take damage yeah
checking tag first and then grabbing for DamageSystem is better. b/c the way u have it now it'd try to grab the component from everything
vs just the things u know will have that component
hey guys, any idea why this happen? I instantiated the square several times as a prefab to form the rows and columns, but some lines don't render coorectly
Thanks man it works
Sorry what?
TryGetComponent and simply damage whatever's hit, unless there isn't friendly fire. Could probably filter relative to layer as well though using the physics matrix
without the tag check
it will run GetComponent on everything it happens to Collide with (enter the trigger).. i was just simply saying its better to have that initial tag check first.. so u can limit what its being called on (by using a tag you can check the objects you already know will have the Component ur lookin for
but .. u've already added it back.. so no worries
Looks like a camera issue where pixels are being misinterpreted
how can i fix it?
i'll read that thanks
He i am trying to deactivet the canvas with the game overscreen. But when i click gameover it doesnt dectived
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ButtonClickDetector : MonoBehaviour
{
public Button myButton; // Reference to the Button
public GameObject gameover;
void Start()
{
// Make sure the button is assigned
if (myButton != null)
{
// Add a listener to detect when the button is clicked
myButton.onClick.AddListener(OnButtonClicked);
}
}
// Function called when button is clicked
void OnButtonClicked()
{
Debug.Log("Clicked");
gameover.SetActive(false);
}
}
``` How can i fix that?
maybe myButton is null? have you debugged this code
did you assign myButton and gameover in the inspector?
did "Clicked" appear in the console?
what this code do?.
if(!attachTransform)
{
GameObject attach = new GameObject("offset");
attach.transform.SetParent(transform, false);
}
its creating a new gameobject at runtime and assigning it as child to whatever spawned it / created it, if attachTransform is null
you would probably assign it to attachTransform after creation
eg attachTransform = attach.transform
the false flag on the SetParent makes it so it doesn't retain the worldPos
how can I prevent visual studio code from opening that window on the left and giving these messages on the bottem?
Finish configuring it
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
there is not Unity API Reference in my help menu
Hello sorry I need help, I was trying a character controller from youtube. For use it I open a scene called Demo, and work from it. But when I close Unity and Open it again, scripts dont work. Anyone knows?
Shouldn't Facing.Player bleed into Facing.Random when the if statement is false? case Facing.Player: if (Random.Range(0, 1f) < chanceOfFacingPlayer) { controller.FacePlayer(); return StatusMessage.Completed; } case Facing.Random:
It complains and says a break statement is missing
Your question is way too vague
Show the full switch
it's highlighting the }
It will error as your case has stuff in it
You need a break on the final case
Oh yeah maybe you can't drop through with code in the case
No
seems like this
Explain your actual issue
Explain what particularly isn't working and how
"scripts don't work" is too vague
Case fall-through will only happen if you have something like
case A:
case B:
// stuff
It's in Java that fall-through is unresricted, IIRC
Add goto case Facing.Random; at the end to force fallthrough
unity cant add script component because the script class cannot be found
I got this error
bool a = true;
bool b = false;
if (a == false)
{
b = true;
}
//B is now true IDK why but if a is and stays true, why does it still go into this if statement and turns b true?
fixed
It doesn't. If b is true, then a is false.
Assuming this is all in the same method
But debug mode still shows how it does enter, even if it is not allowed to and the parameter is still wrong
This here is a simple showoff but I can record a video in the VS Debug mode, how it jsut dont care and turn my variable still true
The debugger lets you hover over the variables to check their values, try to use that.
Thats what I did
Make sure you saved the code and returned to Unity for it to recompile. Make sure you were not in play mode while doing all that
OK I guess I found it but it was something with colliders and NPC FOV. The Player closed the Locker and the NPC cant see him anymore because of the doors. I hope I can make the doors still somehow not seethrough, but seethrough for the NPC so that the player cant hide in this locker while he is in the FOV of the NPC. In my case, the doors closed and blocked the rays of the NPC eyes
why would anyone use GetButtonDown() over GetKeyDown()? I understand not using the new input system cause of its complexity, but GetButtonDown() uses strings as opposed to the much better keycodes of GetKeyDown(), no?
GetButtonDown is useful if you've set up a specific button configuration in the input manager settings
Simple: Gamepads
makes sense, thanks!
likewise
trying to make a bullet destroy an enemy and i made sure via tags the enemy will be destroyed but for some reason it just goes past
How can i Normalize this? When pressing W and D for example, the magnitude is 1.4, however i want the magnitude of the Vectors to always be 1
Construct one vector, normalise it at the end, then multiply by Delta time
Also, consider using input axes (or the new input system) instead of querying for individual keys
So i think the issue i am having is the bullet not spawning in properly and it leads to it spawning where the original object was
When i want it to spawn from the player
What is the usual code to make that result?
Usr the form of Instantiate that accepts a position, and provide the position you want
What causes the situation where opening C# code by doubleclicking a script in the editor will only bring up the IDE with just that class/script and not the rest of the solution?
you gotta add a Quaternion.identity or something else for the 3rd parameter which would be the rotation, and turn the 2nd one into a position instead of a Transform
but you can see this on the docs for Instantiate
!code and whats the problem
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok it says it could be due to corrupt file or anti virus
turn off your anti virus and re install Unity, or just re install Unity normally
Yeah the ‘shooting point’ is that
ok now read the first part of my sentence
and do that
because you are not currently.
Refer to the documentation if needed https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Misconfigured !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 couldn't possibly reinstall an editor in 4 minutes..?
Thanks, I'll comb through this
did you reinstall editor through unity hub? you gotta do that
Offline installation? That could potentially be the cause of the issue.
Just a quick followup, turns out the Visual Studio Editor package for this specific Unity project wasn't installed for some reason, assumed it just came with it so of course installing that did the trick
Perhaps upgraded from an older editor version?
is there a way to check if a variable exists on a scriptable object?
before trying to do anything with a variable that might not exist i mean
You should access the SO in a way that ensures the variable exists, like with an interface . . .
Using a script, im trying to rotate an empty parent object, so that the children rotate with it. However, the children do not seem to rotate with the parent. Is there any reason why? Let me know if the code is needed
What do you mean by "exists"?
And how are you gonna do something with a variable that you don't know exists or not.
Kinda hard to say anything without knowing the context, but a wild guess is that the child object has a dynamic rb..?
It should be kinematic.
Though, I'd assume there is a reason why it's dynamic, and making it kinematic would break something else in your setup.
I dont think it will, i dont have any script moving the children specifically
It works now, thank you so much!
i was using the ScriptableObject type on a custom scriptable object when declaring it and wanted to use the variables from it
turns out i had to cast it i think it was called
like this
Or just declare it as the right type in the first place. Unless there's inheritance involved?
not quite... i dont think? this is the implementation
im sure there is a better way of going about it but im just rushing through this task
I wouldn't use ScriptableObject for heldItem.
Just declare it as WeaponScriptableObject.
but what if i want to use a GenericScriptableObject later in the else statement
Then make a base class that has common fields/properties, like an 'itemSprite`. This way you wouldn't need to cast anything.
and make the ....ScriptableObjects inherit from it?
No. Make the base class inherit from ScriptableObject.
pickupscript?
Item : ScriptableObject
WeaponItem : Item
Etc...
ah yeah i see what you mean
You could abstract the type one or two layers deeper, then reference EquippableItem instead of ScriptableObject.
if (heldItem is WeaponItem weapon) { sr.sprite = weapon.sprite; }
is this what you were talking about dlich or did i do it wrong?
im guessing ill have to change the script name too if im doing it like this
It’s correct, but each SO type needs to be on its own script yes
oh it does?
I think it's fine in the latest versions of the editor, but I'd still put them in separate files.
Maybe that’s changed on recent unity versions. Try it
im probably wrong but does this then kind of work like polymorphism where if i try to access the weaponType, it will know which SO its meant to be?
not polymorphism
bruh, inheritance
im too tired lol
Inheritance is a feature that allows devs to use polymorphism
im learning them both rn at uni and im getting the terms slightly jumbled together
do you mean that inheritance comes with a form of polymorphism built in?
Which allows you to reference inheriting types as types of smaller depth
Polymorphism is when you assign apple to var of type fruit
Inheritance is when you inherit fruit from apple
It doesn't "know what it's meant to be", it's actually an object of that type. It's like having an apple and giving it to someone saying "take this fruit". Despite you calling it a "fruit", it doesn't change the fact, that it's actually an apple.
Polymorphism wouldn’t work if inheritance didn’t exist
that makes sense
we basically only touched on polymorphism in terms of copying a method but adding a new variable passed into it
like Attack() and Attack(bool ranged)
That’s not polymorphism lol, that’s called method overloading
is that not part of it?
Polymorphism is just that
damn i need to reread the material 😭
It would be polymorphism if you were to override the Attack() method in an inheriting class.
oh so
protected override thingies
Or public
👮
Friggin’ auto correct lol
how does public tie into polymorphism?
It doesn't. It's just an accessor modifier.
oh wait you mean public override right?
iirc it has to be the same access modifier as the method in the base class right?
Is this like the first week in uni? 😛
2nd year 😢
i only started sleeping like 2 months ago tho so might as well be
I laughed coz there’s no way I can type fast enough to satisfy a new dev’s curiosity xD that was refreshing lol
Ohh. Then you’re getting to the good parts now 👍
The point is that almost any accessor modifier would do, aside from private, as it limits the method visibility to only inside the class itself.
No I mean OOP
because if it was private you couldnt call it from the base class anymore right?
If it was private you wouldn't be able to call/access it from anywhere aside from where it is declared.
More like inheriting classes should be aware that the method exists, and it’d be confusing if they did even if we added “private” there, so Microsoft prevented that, and made private members only accessible on EXACTLY the same type — not derived ones
Then added the protected modifier to allow ONLY derived types to access members marked with it
Guys does static batching work for instantiated objects at all? Prefab is marked as static, but i also tried StaticBatchingUtility.Combine() it but the meshes are still drawing separately, despite material is the same :[
Also if I enable GPU instancing on the material they start drawing instanced despite dynamic batching is disabled in Player Settings.
Uh oh batching is so confusing
Why are you using a static GO btw? Curious
No. Unless you perform the batching at runtime manually.
Also instancing and batching are 2 separate things.
Good talk :p
I want to combine all these containers into a single draw call. So shall I like GetComponent for all the renderers in the containers and combine them with StaticBatchingUtility?
Sure? That’s not what I asked tho
Like why is it static in the first place?
the approach you described would work
I thought Unity will combine them if I mark it as static
Ahh.. no it does some optimizations for static objects but if you have specific optimization specs you might wanna handle them explicitly
is .Count the same as .Length but for lists?
I see, thanks much!
Np. I’d recommend using a mesh combiner (coded or found online), and THEN mark the NEW COMBINED GameObject as static.
Only at editing time. The batching happens during the build or when you play the scene in the editor.
it's a bit weird at first, I got confused why .length wasnt working when I first tried lists
You’ll eventually stop using arrays completely lol, so it’s fine 👍
im assuming this task is no different from what i just did with the items right?
aside from the logic part
It can be. Or you could use separate unrelated class and hardcode everything. Up to you.🤷♂️
Kinda. Making a base class Trap and utilizing polymorphism is a great practice — and big educational step forward
Trap > FireTrap / WaterTrap / ElectricTrap etc
Go ahead and do the base class and ask here for feedback if u want
The idea is to need to write as little code on derived classes later as needed
(While respecting the base type’s standalone-ness, that is)
I think what I'll do is track the player's position in game manager and then check it against the position of the trap, then the only thing we override will be the message in the debug
Nice try, but google Unity OnTriggerEnter (or +2D)
Just reading through this too and was confused why it needs to be a SO and not 2 classes?
For the benefits of having it as an SO obviously. Like being able to create instances of it as assets.
Not obvious to me, still having a hard time understanding SOs
Basically, you have MonoBehaviours that you can create instances of as components on gameobjects in prefabs or scenes. And then you have SOs that don't need to be attached to anything and can just exist as assets in the project.
I don't understand SOs, so a question: Wouldn't that be the same as creating an empty gameobject and adding it to the components? Or is a SO just not an actual gameobject?
They are pretty similar apart from the slight overhead of gameobjects requiring more data and a transform attached to them.
Ahh that explains it. I'm an older dev whos returning from the heyday of 2014 with Unity so a lot of this is new to me but this explains it well. Just a little less boilerplate to having to create and set up prefabs basically. And probably some other niceties
It would be similar, but why waste memory and some overhead on an object if you only need that one class instance?
Interesting, I'll look into SOs, they seem useful, I just use empty gameobjects for components 😭
Never knew what SOs did previously, so never used them
I've got an issue where I have a singleton being assigned in awake and other scripts want to subscribe to events on the singleton during their onenable
but the singleton assignment happens after the onenable of the other scripts, which I didn't expect
so they try to subscribe to a null instance
I haven't changed script execution at all but would that solve this?
feels hacky to do so, though
I changed script execution order and it fixed it
sometimes its necessary but the design could be better
but I wish there was a more robust way to do it
proper dependency injecting
I looked it up and apparently the execution workslike:
obj1 Awake
obj1 OnEnable
obj2 Awake
obj2 OnEnable
which is inconvenient :)
I'm not sure what this would look like in practice
who would do the dependency injecting?
other objects in previous scenes usually boostrapping
I don't know what that is
Alright gentlemen, I have figured out how to spin a Motor
but now I am having big problems trying to simulate Torque and Load
physics are a pain
I gave up on physics, I am just using scripts to do it
One script controls the Rotation, the second script is suppossed to do Torque
The Rotation with Inertia works just fine, when you try to add Torque into the mix all hell breaks loose
The Inertia part btw is VERY Rudimentary, it just increases speed over time
instead of being a physical force
does anybody have a clue what this error means? it just randomly started showing up
It's originating from the editor, just clear it and move on
would it still let me build the game with this error
i just wonder... do i even need to save the state of my serialized objects to disk?
In what context?
i mean. arent they already serialized? i just wonder because i try to save them to my json save file
to track progress
Serializing doesn't necessarily mean saving. Unity does serialize and save (serializable)objects state in some scenarios. For example objects in the scene, prefabs and SOs at editing time
this implies these values are changing, you shouldnt modify data of an SO. they work differently in a build compared to editor.
either dont use an SO or rethink the system so that you arent modifying the SO data.
in editor they "save" because you're directly modifying the asset, which doesnt work in a build in the same way
oh ok thanks
hm... how do they work in build?
i have a scriptable object that saves a dictionary of a string and a dataobject. is that scriptableobject rebuild on every start? because i somehow need to save a reference of the dataobject at some point..... ||unless i get a complete new reference||
In the build, everything is an immutable asset. It's not expected to change between the sessions.
they will reset back to their original state across new sessions yes. still use your existing json method but just dont change the SO data, theres no point.
if you need the SO, you can copy its data to a plain c# class and then just modify/save that.
If you want to save something between sessions, you need to implement a saving system.
yeah.. it is probably easier that way anyway
HI ! I'm working on unity 2022.3.37, i want a gameobject to rotate (only on the vertical axis) in the direction of my vector3.
Let's said you have a gun, you shoot on a wall, the shootPoint is a vector3 and there's a compass on the ground which rotate in the direction of the shootPoint.
How could i do that ?
I've tried something like that but it rotate on the Z axis
Vector3 direction = shootPoint - compass.transform.position;
// Ignore the Y component to rotate only on the vertical axis
direction.y = 0;
// Check if the direction is not zero to avoid errors
if (direction != Vector3.zero)
{
// Calculate the target rotation to point towards the shootPoint
Quaternion targetRotation = Quaternion.LookRotation(direction);
// Apply the target rotation, keeping the rotation constrained to the Y-axis
compass.transform.rotation = Quaternion.Euler(90, targetRotation.eulerAngles.y, 0);
}```
Quaternion.LookAt(forward, up)
but how do i say "look at that direction" ?
what you say just tell the gameobject to look in front of him right ?
transform.rotation = lookat
You still need to tell it which direction forward is
transform.forward would be forward (local space)
to look at a thing, forward = posOfThing - posOfObserver
So it's my variable direction right ?
I sus it might
where did this code come from?
basically i have to replace "LookRotation" to "Lookat" ?
combination of stuff i found online
well, fyi, this
// Apply the target rotation, keeping the rotation constrained to the Y-axis
compass.transform.rotation = Quaternion.Euler(90, targetRotation.eulerAngles.y, 0);
will never work
why ?
you should never use quaternion.eulerAngles as INPUT into any method
Okay ! Thank's !
gotta still thank u for this.. lmao.. its burned in my memory now
glad you got it, I spent an hour the other day explaining why this was the case and at the end OP would literally not believe it was true. Then blamed me when it didn't work
how come? can you link the explanation on why? 😛
gives inconsistent results
different values can be the same rotation..
gets whacked out
but he can probably give u a more technical reason
yeah I experience this every time 😦 I usually end up with stuff like in here: #archived-code-general message
whereas stuff like this would be so much more intuitive but fail:
(note: the code is extra condensed for the practical purposes of linking to discord)
i dont get it why there is .eulerAngles getter in the quaternion
so provided the rotation is around a single axis? idk about other right ways
It's really very simple
Vector3 A (euler angles) -> Quaternion -> Vector3 B (euler angles)
because a Quaternion can be represented by many euler angle combinations the chances of A == B is virtually none.
So when you put euler angles INTO a Quaternion and then get euler angles OUT what you are getting will almost certainly not be what you expect
Therefore: do NOT do it!
thats why i question the presence of said getter ;D
indeed. getter for display purposes ONLY
display of... incorrect results? or am i missing something obvious
yes, but they can be a useful visual aid as long as you realize what you are looking at
the point is the results are not 'incorrect' just not what you expect
imo it's not the getter that's wrong architecturally.. it's how Unity handles rotation
no, thats just the way Quaternions work, Unity has no control over that
unity handles rotation just as the rotation should be handled
i use eulers all the time.. alot of the time they're fine..
(tried with constructing a rotation matrix manually then comparing to unity's rotation. Results were equal)
I don't know.. they handle Quaternion operations correctly, but if u set eulerAngles instead it could use a random quaternion that's not related to your previous frame's data
I definitely see room for improvement there, but could also be brushed off as just QOL and nitpicking
(e.g. if you do Quaternion.MoveTowards it'll respect the current state)
all you really need is quaternion.angleaxis and quaternion.lookat
no, only if you read the eulerAngles, test/change them and then set back, that will not work
Quaternion.LookAt is bleh 😛
AngleAxis is all you need tbh
actually it's non-existent 😛 transform.LookAt is the bleh one
a nice learning task would be re-creating LookAt behavior by using AngleAxis only. helped me to understand how to use quaternions
yeah but honestly the only thing that's handled correctly is the multiply operation
someNewQuaternion * transform.rotation
-- if you care about the previous state, that is
in fact its just 3x3*1x3 matrix multiplication (correct me if im wrong)
if u ever really wanna learn quaternions build a telescope, anti-aircraft gun, or anything like that that rotates on 1 axis and then on another.. (seperately but together to track a target in 3D space)
w/ limits and all that.. it'll test ur sanity as well
yeah it's wrong -- you're thinking about Matrix4x4.TRS() https://docs.unity3d.com/ScriptReference/Matrix4x4.TRS.html
rotation is just one line in that matrix -- that transform matrix
ok thx
I dont know quaternion math but just saying 3x3 matrix * 1x3 matrix is not even valid for multiplication
really? i may messed something up, but was pretty sure that A rows and B collums have to be the same
The numbers are the other way around, should be 3x3 and 3x1
righht, thanks
Anyways yea most rotation problems can be solved using like 3 different quaternion functions, most dont really need to know the actual math
The actual math is quite complex to begin with
or you could multiply a 1x3 with a 3x3 lol.. order matters here -- same with quaternions
Hey guys, Microsoft Visual studio or Visual studio code. Which one is better to use with Unity?
!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)
Visual studio at least in the recent past has been better for stuff like using the debugger.
Lots of people here had issues about vs code breaking randomly or just not working
q1 * q2 = (w1w2 - x1x2 - y1y2 - z1z2,
w1x2 + x1w2 + y1z2 - z1y2,
w1y2 - x1z2 + y1w2 + z1x2,
w1z2 + x1y2 - y1x2 + z1w2)
Okay thanks for replying @eternal needle
so (q1 * q2) != (q2 * q1)
yeah VS is the best C# IDE atm imo. Rider comes second and VSCode comes third
- RIDER
- VS
- VSCODE
pfft, nu-uh.. i only use Rider during free-early passes 😄
i had issues with VSCode randomly not-connecting to language server for no reason, but it was in UEFNxVerse, most likely its more stable for Unity, but still wouldn't be surprised if it breaks
i always talked bad about VSCode until i started using it for programming circuit boards.. started liking it so much i use it as my default IDE for everything now
I use Rider on my Macbook and Linux machine where actual VS isn't supported. I get frustrated every time.
Rider is great for telling u how bad u code
but gotta respect the fact that it works, lol. It's quick too
can someone help me with this visual studio code problem?
friggin' Rider code practice assumptions man
just click the open tab to close it..
Vscode was never bad. It's just not well supported in unity. I use it for literally everything else
i tend to treat VSCode as basic lightweight code-editor tool, while VStudio as entire IDE for making builds, project configs etc. Ig as long as Unity handles building for us, these two are pretty much equivalent
it literally autoformats my .AddListener(() => { return 2; }) into:
.AddListener(
() =>
{
return 2;
}
);
heck ya.. i was gaslit at first
ppl making me think its no better than notepad++ or notepad even
if you don't like something just change the setting?
sadly they have lots of code practices hardcoded on their autoformatter
ya, u can disable that stuff.. altho i never got around to it.. b4 my trial expired
Like what? I've not seen anything you can't just set
yikes.. rider did that?
But you just change your braces style in the settings and it won't do that
as with any sensible IDE
its helping u out for when u need to go in and add to that 😛
one liners? hell nah son
yeah I got an official response from the rider team, saying they don't wanna bother adding settings for some stuff
e.g.: { Debug.Log("OK"); return 2; } is not gonna be supported
thats one thing i like about VScode.. u can go in and modify and create json files w/ all the settings / modifications u can think of
tank mechanics are great for this
im done w/ it for a good month or more..
it broke my brain
rofl
Um... Tower defense? :v
Ye I mean making tower defense turrets should be the most basic thing to do with quaternions
that's cheating, a tank does not have a fixed position/rotation body
next time i want to torture myself i'll add some tank tracks..
but as far as i know its all local space
should work fine 👍 😝
tell you what, and this applies to anyone, when you have successfully implemented a working tank controller you can consider yourself a 'Master of Rotation'
But there is no roll, only yaw an pitch. I'd say a working spaceship controller would make you a true master
of course there is roll
and I just downloaded Unity 6 preview for Junior programmer from Unity Learn.. is that okay?
Spaceship is easier than tank, spaceship has free rotation on all axis, tank does not
Oh, right. Roll of entire tank. Makes sense
mines a bit too complex for turret defense.. i was trying to figure out how they lead the target and get the shots to hit
just an exercise.. was welll worth it.. b/c thats when it finally sank in about what steve had been saying about eulers
Predictive aiming ❤️ was it difficult to make it always hit the target?
where does VSCode store it's global settings.json file?
i know each project has one inside the .vscode folder.. but i modified my line-numbers w/ a "workbench.colorCustomizations": { "editorLineNumber.foreground": "#ffff", } block like this.. and it applies to all my projects.. just can't remember how i found it
very much so..
sometimes it still misses b/c its using rigidbody projectiles
but that is good, just like irl
theres more code on the target than the bullets (it takes its velocity each frame and predicts where it'll be by the time the bullet would travel X distance
Was doing something similar in uefn TD game mode. Can confirm that it was difficult as well ;D for linear target movement it was always a hit, but if target suddenly turns, well... I'm not proud of it anyways lmao
void Update()
{
if (rb && aa_location)
{
float distanceToTurret = Vector3.Distance(transform.position, aa_location.position);
float timeToPredict = distanceToTurret / speedOfIncomingBullet;
Vector3 futurePosition = transform.position + rb.linearVelocity * timeToPredict;
if (rb.useGravity)
futurePosition += 0.5f * Physics.gravity * Mathf.Pow(timeToPredict, 2);
if (marker)
marker.transform.position = futurePosition;
}
}
public Transform GetSpecialMarker() => marker.transform;
``` well actually its simpler than i remember
ohh im pretty sure mine has to be on a straight flight path...
or else the turrets gonna just be wasting ammo
Yep
but my system sucks.. b/c the bullet has to ask the turret each frame.. what the projectiles speed w/ be and then do its prediction
and then the turrets always searching for projectiles
not the best..
if you look at how a real ack, ack gun works, it leads the target, calculates the distance of the miss and then moves the aim back
😅
Isn't that to keep things realistic, bullet should ask tower just once, right before a shot?
bullet gets fired.. (and finds tower)
it asks the tower what the projectile speed will be..
then takes it's current velocity and projects where it will be when that speed will cover that distance.. then it just projectiles a invisible sphere collider out in front... the turret just constantly aims at it and sprays
my little hacky way... (so its not actually aiming in front.. its aiming directly at...) a projectile that isnt there
I guess it's sufficient for a game ;D
✅ Solved...
the local settings.json is in .vscode in ur project directory..
the global settings.json is in ur AppData/Roaming/Code directory..
navigated to via Ctrl + , and clicking top right icon labeled Open Settings/UI
💯 .. but its a prop piece for now.. (environmental/cutscene type gadget) when i fix up the nasty code, i'll most likely just give it away as an asset on github or itch
Sounds like a lot of time decoupling and abstracting out if you already have it bound to specific project. Not sure if worth it
But maybe not. I admit that didn't read entire devlog ;p
nah its not tied to anything prefabs for lyfe
ahh, nah i didnt expect you to.. thats just the only place i can find that clip anymore.. (that dev-log is just a mosh-posh of everything i work on here and there..) my production stuff is kept secret for now 😈
dont want people stealing my million dollar ideas 🙄
Ideas can be the most valuable, that's why I don't make own devlog xd (aaaaand... Because don't feel confident enough with unity)
nah, ideas are 10 a penny, the skill to turn them into reality is what is really worth gold
Guys I'm trying to make a keybinding UI, but I'm not sure why the new key does not applied on the input system
https://paste.ofcode.org/pNQECrtLgm6rKMjxwUT3Y3
https://paste.ofcode.org/bwXg9riRgeAbkx2y3zhZFD
Any suggestion?
!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.
how can I do the equivilent of a null check for a static class?
you'll get ther
static nullable bool property
roger, looking up right now
Hello, I have a 3D character with animation and movement through physics. Could you please tell me how to make it so that even if the character bumps into a wall, they can slide off it?
where to do ever set an initial value for currentKey ?
currentKey.GetComponentInChildren<TextMeshProUGUI>().text = e.keyCode.ToString();
with the text
that is not setting a value for currentKey, that is using it to get a value
you have
private void OnGUI()
{
if (currentKey != null)
{
currentKey will always be null
A static class cannot be null
ya, just poor wording
he said 'equivalent' so I guess he knows that
public static class Utils
{
//SETUP
public static bool? IsInstalled { get; private set; } = null;
static Utils()
{
IsInstalled = true;
}```
i came up w/ this
Oh, you mean like checking if it's initialized?
yea, basically.. just didnt know how to properlly word it
if (Utils.IsInstalled == true)
Utils.RealtimeDebug($"Screen Position: X{remappedCoords.x:F0}, Y{remappedCoords.y:F0}", new Vector2(10, 10), 24, Color.white, Color.black, 2, 4);```
because it looks like a null check
not really sure.. im still waking up lmao.. just thinking of ways to make sure my class is in the project w/ some decent logs
What?
If you check if something is initialized there's no reason to have a third state
if (Class.IsInstalled.HasValue) // initialized
else // not initialized
I would assume a static constructor is always called before anything else that is inside the static class
good point
ya, i see your concerns.
The one I sent before was used to change the text on the UI
public void ChangeKey(GameObject clicked)
{
if (currentKey != null)
{
currentKey.GetComponent<Image>().color = normal;
}
currentKey = clicked;
currentKey.GetComponent<Image>().color = selected;
}```
Here are the codes I used to set the new key
i think i got it now 👍 thanks guys
How is this better than just having a normal boolean and checking if it's false instead of null?
i've swapped to that ^
The only logical reason would be because you need a third state, but there are two
personal preference
That's a wild preference
if (Utils.IsInstalled)
Utils.RealtimeDebug($"Screen Position: X{remappedCoords.x:F0}, Y{remappedCoords.y:F0}", new Vector2(10, 10), 24, Color.white, Color.black, 2, 4);``` ya, i was trying to do this originally..
just bad at words, yaknow
but when i seen bool? i just wanted ot figure out what it was exactly lol
I wonder, why do you need to ensure it is initialized? What does this static class contain that requires setting it up?
its just a static utilities class..
Because you can be sure the constructor is called, so this extra check is not required
it doesnt need to be present.. but alot of errors in my codebase specifically if its missing
i'll be honest w/ you... not done many constructors or anything of that nature really..
just now getting comfortable w/ properies and getters and setters and whatnot
That's fine, just interested in seeing the reason for it
so debug it to make sure it's being called
Often a lot of code is added that would make sure the logic is solid, but often it's not required
But this constructor does nothing. I would assume it sets data somehow?
I'm sure its been called after I changed the button
You mentioned that you want to make sure the static class is installed or something. Are you unsure if the static class exists when you try to use it?
yes
Because it always exists. It has no instance so it can't be null
I like to have the option of Yes/No/Maybe, believe it or not it often comes in handy
the code all functions w/o it.
its just little debugging and helper stuffs thats not vital to functionallity. but if its not present i'd like to display a console message or something saying to either add the static class.. or remove the logic that calls upon it
But you don't add it, you literally can't
If you have a static class in your code like this, it will always exist
I'm sure there's some logic to it when it's properly constructed, but it will always be there when you use it
The only reason why you might want to do this is if your static class needs external data that must be initialized, which might be done through some separate "Initialize" method. But you don't have this, and even if you do this would be in the constructor most likely.
And if you had that I strongly suggested you got rid of it because that's bad 
@burnt vapor alrighty, i think i see where ur coming from. I'm doing some more research on it..
So, I have a codebase.
This Static Utils class just has some helper functions and whatnot..
It's would not change the over-all functionallity of the project.. but it would require a bit of refactoring just to remove some of those function calls.
If its not included then obviously they'd be some errors.. I was just trying to make a graceful attempt at allowing the rest of the code to function w/o it being present.. (maybe giving u some logs and stuff)..
and i'd be lying if i said i knew the appropriate way to handle that lol
(still learning)
Well, static classes always exist, so checking if it's not makes no sense
A utils class is a very good idea, that's not an issue
I often make a lot myself
well, the project is made up of different pieces and stuff.. (theres a chance the static class doesn't make it into the project)
I don't know what you want me to say other than that it exists no matter what
If it didn't exist, then you would be not even be able to use it because the intellisense could not find it
soo.. if i duplicate my project.. and delete the utils class.. ur telling me it still exists?
For example, if it's in a different unreferenced assembly definition
Then your boolean check would not exist either
touche
Also, your code would not compile
ahh, soo now we're at the culprit..
(to be clear, static classes are initialized when they're first accessed)
It would not compile because it doesn't know what Utils.RealtimeDebug is
say i wanted it to compile.. regardless if that class is ther