#💻┃code-beginner

1 messages · Page 508 of 1

slender nymph
#

did you perhaps make the rigidbody Kinematic? or are there perhaps colliders or friction preventing the object from moving? and have you verified that Acceleration is not 0?

#

collection initializer syntax

rich adder
#

use the {}

rotund hull
#

where would i use {}

zealous junco
rich adder
rotund hull
#

yo boxfriend, you want the smoke?

slender nymph
#

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

rotund hull
#

i did

#

it was a joke man

slender nymph
rich adder
zealous junco
rich adder
zealous junco
#

The debug prints values but the car still wont move

rich adder
#

don't need to crop show it selected in the scene

zealous junco
rich adder
#

make sure forward is not like down or some shit lol

#

might be too much mass and too low acceleration / force

zealous junco
#

Forward stays ths same in local

slender nymph
#

also make sure that your acceleration is high enough to overcome friction

rich adder
#

ya crank that

zealous junco
#

Im so stupid

tender stag
#
// 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

slender nymph
#

you should format those numbers to include more digits because i bet it is above maxWeight due to floating point imprecision or something

tender stag
#

floating point imprecision?

#

looks fine to me

vestal wasp
#

Does anyone know a playlist that will help me make a gacha game

slender nymph
# tender stag looks fine to me

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.

vestal wasp
#

I saw one on it but I think the creator deleted it

sharp abyss
#

why is it red shaded btw

tender stag
#

i changed the play mode color

sharp abyss
tender stag
vestal wasp
tender stag
#

if the item.amount is more than 1

#

if its 1 then it works fine

slender nymph
#

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

tender stag
#

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

tender stag
# slender nymph mate, your code is practically unreadable because of the amount of objects you a...
// 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

slender nymph
#

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

sharp abyss
tender stag
#

my what

sharp abyss
#

maxweight

slender nymph
#

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}.");

north kiln
#

If you're having this much trouble just logging out variables use the debugger and just inspect the variables and outcomes directly

sharp abyss
#

-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

tender stag
#

alright

#

explain to me

#

difference between these two

#

because the top one works

#

even this works

#

its this bit (cell.inventory.currentWeight + itemWeight)

sharp abyss
# tender stag

why did you add item.itemData.Weight * itemAmount to current weight? doesnt it already have them

tender stag
#

for each item u add weight

tender stag
#

its the same thing, i wrapped it in the brackets

slender nymph
#

you have an error in the console that you are ignoring

sharp abyss
slender nymph
#

because i know how loops work lmao

tender stag
slender nymph
#

possibly 🤷‍♂️ inspect the actual values using the debugger to find out

tender stag
#

i mean it works

sharp abyss
tender stag
tender stag
#

u can drag multiple items into cells

glad comet
#

why is this an infinite loop?

frosty hound
#

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?

glad comet
#

no

frosty hound
#

If you comment it out, does it still freeze?

glad comet
#

when i ran it the code just kept running without being able to stop it

glad comet
frosty hound
#

The loop, if you remove it, does your game still freeze?

glad comet
#

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

frosty hound
#

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.

glad comet
#

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

frosty hound
#

Ah yes, sorry, I'm playing games so I was skimming the code

grave bluff
#

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

grand badger
grand badger
grave bluff
#

interesting

#

straight up UI_element.transform.position can be thrown into the line renderer and it just works? kinda crazy

grand badger
#

Or maybe you need to do Camera.main.ScreenToWorldPoint lol.

grave bluff
#

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

deft grail
grave bluff
#

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

olive beacon
#

Can anyone help me figure out why nothing is outputted to my Debug Log here:

orchid fjord
#

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();
    }
}
eternal falconBOT
deft grail
olive beacon
orchid fjord
deft grail
orchid fjord
deft grail
orchid fjord
glad comet
#

I'm trying to create a random vector and apply it to a game object but the code wont work

deft grail
#

is there an error?

glad comet
#

yes

#

let me get the error

deft grail
#

ah

#

i think i can guess

glad comet
#

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

olive beacon
glad comet
#

the last one i understand

deft grail
#

timer is an int but it should be a float

glad comet
#

such a simple one

#

oof

orchid fjord
#

It gives me this, hower there is like a second or 2 between the 2nd clip starting

glad comet
#

thanks

deft grail
glad comet
#

thank you

#

i still cant get the middle chunk of errors though

#

all on that "randomPositon" line

deft grail
#

not when intializing the variable

#

make a new method SetRandomPosition() or something, or do it in Start if you do it just once

glad comet
#

I keep making that mistake. Let me see if I can solve the last few errors.

grave bluff
grave bluff
#

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

olive beacon
#

and a working thingy is all we need

grave bluff
#

it turns out transform.position on a ui element IS the correct world position

#

no rect handling needed

glad comet
#

how do I get my code to ask for a rigidbody2d that I can drag and drop into the script component in the editor?

deft grail
#

or you can do [SerializeField] private instead of public

glad comet
#

i think im doing this but its still not asking for the rigidbody

#

im sending the code

glad comet
deft grail
deft grail
#

do you have any errors in the console

glad comet
#

yes

deft grail
#

then you need to fix them

glad comet
#

only one error that says that im not referencing rigidbody

deft grail
#

otherwise scripts cant compile

#

what error

glad comet
#

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?)

deft grail
#

because its supposed to be body

#

not Body

glad comet
#

thanks

#

that worked

#

i think im really tired

deft grail
eternal falconBOT
glad comet
fading vigil
#

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

rocky canyon
#

is it a character controler?

fading vigil
#

'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

rocky canyon
#

u cant teleport a character controller

#

need to disable it move it and reenable

fading vigil
#

So I have to disable all character movement and then teleport

rocky canyon
#

basically yes

#

disable movement/input teleport it.. and re-enable

fading vigil
#

is there a way to disable scripts for a short time?

rocky canyon
#

scriptReference.enabled = false;
characterController.transform.position = newPostion;
scriptReference.enabled = true;

#

u can do it all in the same frame..

fading vigil
#

Alright thanks

glad comet
#

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

cinder schooner
#

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.

glad comet
#

thank you

cinder schooner
#

you're welcome!

near wadi
#

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

unique canyon
#

oh got it thanks!

near wadi
#

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

teal viper
#

Fork is a decent one@near wadi

autumn pine
#

does anyone know how I can restrict the generated PlayerInput C# class to use only one control scheme

near wadi
dusty shell
#

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

teal viper
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

dusty shell
ruby python
#

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?

Watch "2024-10-13 07-14-39" on Streamable.

▶ Play video
tame valley
#

um the variables dont show up in inspector, anyone got solutions? :\

eternal needle
tame valley
#

oh it worked, thanks so much!

solar arrow
#

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);
    }

languid spire
#

don't normalize the vector

solar arrow
languid spire
#

do you know what normalize does?

solar arrow
#

makes value to 1?

languid spire
#

no, makes magnitude = 1

solar arrow
#

oh okay

#

btw still doesnt work

ivory bobcat
solar arrow
ivory bobcat
#

Don't normalize it.

solar arrow
#

i dont

ivory bobcat
#

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.

solar arrow
# ivory bobcat What's the issue then?

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

languid spire
#

the normalize was what was causing the 1 to become 0.71 so where is the problem now?

ivory bobcat
#

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)

solar arrow
#

so its the ReadValue that normalize it?

#

its a function inside of unity

ivory bobcat
#

Or round round up to one etc

#

Check the mathf class for Unity

solar arrow
unique nymph
#

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

languid spire
#

get the objects to subscribe to an event, then fire the event when the change happens

shrewd matrix
#

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;
    }
}
languid spire
#

wot no print

shrewd matrix
shrewd matrix
#

or up

languid spire
#

do you have a GraphicsRaycaster in your scene

shrewd matrix
#

i dont i only have a event sytem

languid spire
#

then I suggest you go and read the docs on the IPointer interfaces

shrewd matrix
#

alr

fading vigil
#

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;
                }
        }

    }
        
}
eager spindle
#

Could you tell us what's wrong with the code first?

#

And what it's supposed to do

fading vigil
#

It sometimes doesn't teleport you

languid spire
#

start by debugging it

fading vigil
#

And sometimes blinks teleport so it just blinks but doesn't teleport

fading vigil
eager spindle
#

Do all your walls have the wall tag?

fading vigil
eager spindle
#

What's playercode supposed to be?

fading vigil
languid spire
#

more to the point, why are there 4 GetComponents on it in Update?

fading vigil
languid spire
#

that does not explain why there are 4 of them in Update

eager spindle
fading vigil
#

just character controller

languid spire
#

if you have CharacterController why use transform.position?

eager spindle
#

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

eager spindle
#

Does PlayerCode inherit from CharacterController?

fading vigil
eager spindle
#

do you know what inheritance means

fading vigil
#

or am I wrong?

eager spindle
#

In your code you see something like public class PlayerRayCast : Monobehaviour, PlayerRayCast inherits from Monobehaviour

#

What does PlayerCode inherit from?

fading vigil
#

MonoBehaviour

eager spindle
#

I see

#

In that case you should be disabling CharacterController

fading vigil
#

[RequireComponent(typeof(CharacterController))]
Also there's this

eager spindle
#

Not PlayerCode

eager spindle
fading vigil
eager spindle
#

I'm not sure what disabling PlayerCode does for you, but you should be disabling CharacterController instead

fading vigil
#

Alright thanks a lot for the help

covert glacier
#

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;
    }
languid spire
short hazel
#

You can also declare the parameter as a bool instead of an int to simplify that code

proven matrix
#

Why does my character always fall through despite having a box collider on the grid and the player

slender nymph
covert glacier
slender nymph
#

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

covert glacier
slender nymph
#

well that tells you it's likely some code on the one that causes it to freeze

covert glacier
#

it not really a lag freeze, just that I cant click anything/the UI doesn't update

slender nymph
#

you can't say "freeze" when you mean "everything still works except for UI"

covert glacier
mellow rose
#

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

slender nymph
#

screenshot your entire visual studio window with the solution explorer visible

mellow rose
#

ok

spiral abyss
#

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

spiral abyss
#

k ty

mellow rose
#

aah I see incompatible

slender nymph
# mellow rose

this shows that something you have selected is not installed, are you sure you've installed the game development with unity workload already?

mellow rose
#

I mean, I'm not sure I can make the tick next to the Game development with Unity any more... tickier :p

slender nymph
#

just ticking the box doesn't install it. you have to actually click the install button

mellow rose
#

Yes 😛

#

(I'm aware)

slender nymph
#

okay well again, something you have ticked is not installed which is why i brought this up

burnt skiff
#

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

slender nymph
#

!ask

eternal falconBOT
mellow rose
burnt skiff
slender nymph
# mellow rose

what version of the visual studio editor package do you have installed in unity

mellow rose
slender nymph
#

that does not answer the question i asked

mellow rose
slender nymph
#

and you have completely closed visual studio and restarted it after having regenerated project files?

mellow rose
#

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... 🥲

slender nymph
#

right click the project in visual studio and select Reload With Dependencies

mellow rose
#

that worked. 👍

#

thanks

#

I usually just use visual studio code 🥸

burnt skiff
#

anyone have any experience in doing simple simulations in unity

slender nymph
burnt skiff
#

oh sorry

toxic void
#

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

keen dew
#

Array sort is a static method for the Array object. Array.Sort(positionArray, ...)

toxic void
#

oh, thank you

keen dew
#

If you use LINQ it'll add methods to arrays

toxic void
#

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

keen dew
#

I don't know if Vector3 has a default comparer implemented. You probably need to pass in your own

wraith hill
#

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)

ivory bobcat
wraith hill
ivory bobcat
#

Your component script

#

If square has a render board, the Unity Editor will crash on attempting to play

wraith hill
#

aaah

#

i get it

#

wait

ivory bobcat
#

Right, so you'll make infinitely many squares

#

Thus you'll freeze the editor

wraith hill
#

aaaah I get it, thanks, so maybe move the script to the game manager, right?

sterile wolf
#

Guys so i have a question can i use python in unity ?

#

instead of c#

wraith hill
languid spire
#

not really, no

sterile wolf
#

oh okay i see thanks

wraith hill
cinder gazelle
#

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 ?

burnt skiff
#

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

slender nymph
#

show that it is actually assigned on the object and not just as a default reference for the script file

latent ore
#

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;
   }```
slender nymph
#

okay now show what i asked for

burnt skiff
#

which one is that

slender nymph
burnt skiff
#

ohhh alright

slender nymph
latent ore
slender nymph
#

assuming that you have actually called the method that adds the listener, and that the volumeSlider and musicBackground variables are assigned

slender nymph
#

show it

latent ore
#
   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);



   }
slender nymph
#

and where do you call StartGame?

latent ore
#

somewhere close to the bottom

#

its organized alphabetically

slender nymph
#

wdym? i'm asking where it is called not where you've placed that method in the class. just show the full code

latent ore
#

im not calling it anywhere, its the same as start

#

should I call music() in update?

slender nymph
#

it's not the same as Start . . .

languid spire
#

why would you think Start() and StartGame() are the same thing?

latent ore
#

oh yes you're right sorry i mixed it up with update

#

startgame is called in start lol

ivory bobcat
slender nymph
#

and you have confirmed that is actually being called

latent ore
#
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

verbal dome
latent ore
#

figured it out

#

had to call it in update

verbal dome
#

I suppose you are drawing it in world space while you need to convert it to local

slender nymph
cinder gazelle
#

I'm good i found a solution after some time but thanks

slender nymph
sterile wolf
latent ore
#

why not?

#

doesn't it need to continuously check for the slider value?

languid spire
slender nymph
sterile wolf
languid spire
#

no, it's crap

sterile wolf
languid spire
#

these are questions you should be asking Google, not us

latent ore
#

I guess I didn't realize that the start function is it's own thing

pastel sleet
#

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);
        }
    }
}
slender nymph
deft grail
#

this code alone seems fine

pastel sleet
deft grail
pastel sleet
#
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;
    }

}
deft grail
pastel sleet
#

yeah sorry

#

still not good at c#

#

stil Experimenting

pastel sleet
deft grail
#

it doesnt need to be there, it doesnt make sense to be there

#

the OnTriggerEnter

pastel sleet
#

in the DamageSystem script?

deft grail
#

yeah

languid spire
#

also dont call TakeDamage in Update

pastel sleet
#

oh oke

pastel sleet
# deft grail just remove it completely

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
    }
        
        
    }
}


deft grail
#

test it and see if it works

pastel sleet
#

oki

#

wait one sec

#

wait i see the problem

pastel sleet
deft grail
#

other.gameObject.GetComponent<DamageSystem>().TakeDamage(10);

pastel sleet
#

here is a video

deft grail
deft grail
#

prefabs cant reference scene objects

pastel sleet
#

oh oki

pastel sleet
deft grail
#

where you want to take damage

pastel sleet
#

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);
    }
}
deft grail
#

but thats how you would take damage yeah

pastel sleet
#

I have put them back

rocky canyon
#

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

wraith hill
#

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

pastel sleet
ivory bobcat
#

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

rocky canyon
# pastel sleet Sorry what?

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

ivory bobcat
wraith hill
dim yew
#

ScreenToWorldPoint seems to always return these 3 values

#

any idea why?

slender nymph
dim yew
#

i'll read that thanks

pastel sleet
#

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?
cosmic quail
#

did you assign myButton and gameover in the inspector?

#

did "Clicked" appear in the console?

glossy turtle
#

what this code do?.

#

if(!attachTransform)
{
GameObject attach = new GameObject("offset");
attach.transform.SetParent(transform, false);
}

rich adder
#

the false flag on the SetParent makes it so it doesn't retain the worldPos

woven stump
#

how can I prevent visual studio code from opening that window on the left and giving these messages on the bottem?

eternal falconBOT
woven stump
tight cradle
#

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?

blissful yew
#

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:

wintry quarry
#

Yes

#

It will

blissful yew
#

It complains and says a break statement is missing

wintry quarry
wintry quarry
blissful yew
#

it's highlighting the }

short hazel
#

It will error as your case has stuff in it

wintry quarry
#

You need a break on the final case

#

Oh yeah maybe you can't drop through with code in the case

tight cradle
#

could I dm you?

wintry quarry
#

No

blissful yew
wintry quarry
#

Explain your actual issue

#

Explain what particularly isn't working and how

#

"scripts don't work" is too vague

short hazel
#

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

blissful yew
keen dew
#

Add goto case Facing.Random; at the end to force fallthrough

blissful yew
#

Nice!!

#

I knew there was a way to do that

tight cradle
#

I got this error

spring skiff
#
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?
tight cradle
short hazel
#

Assuming this is all in the same method

spring skiff
#

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

short hazel
#

The debugger lets you hover over the variables to check their values, try to use that.

short hazel
#

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

spring skiff
#

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

gleaming kraken
#

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?

slender nymph
#

GetButtonDown is useful if you've set up a specific button configuration in the input manager settings

gleaming kraken
somber marten
#

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

tulip nimbus
#

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

north kiln
#

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

somber marten
#

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?

wintry quarry
cunning narwhal
#

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?

deft grail
#

!code and whats the problem

eternal falconBOT
deft grail
#

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

somber marten
wintry quarry
#

and do that

#

because you are not currently.

eternal falconBOT
teal viper
#

You couldn't possibly reinstall an editor in 4 minutes..?

cunning narwhal
steep rose
#

did you reinstall editor through unity hub? you gotta do that

teal viper
#

Offline installation? That could potentially be the cause of the issue.

steep rose
#

in the hub to to installs, and click install editor

#

then click the version you want

cunning narwhal
# teal viper Misconfigured !ide

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

teal viper
#

Perhaps upgraded from an older editor version?

rancid tinsel
#

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

cosmic dagger
arctic ridge
#

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

teal viper
#

And how are you gonna do something with a variable that you don't know exists or not.

teal viper
arctic ridge
#

Ill check real quick, totally possible

#

Yup! I assume it should be static then?

teal viper
#

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.

arctic ridge
#

I dont think it will, i dont have any script moving the children specifically

#

It works now, thank you so much!

rancid tinsel
#

turns out i had to cast it i think it was called

#

like this

teal viper
rancid tinsel
#

im sure there is a better way of going about it but im just rushing through this task

teal viper
#

Just declare it as WeaponScriptableObject.

rancid tinsel
#

but what if i want to use a GenericScriptableObject later in the else statement

teal viper
rancid tinsel
#

and make the ....ScriptableObjects inherit from it?

teal viper
#

No. Make the base class inherit from ScriptableObject.

rancid tinsel
#

pickupscript?

teal viper
#

Item : ScriptableObject
WeaponItem : Item
Etc...

rancid tinsel
#

ah yeah i see what you mean

grand badger
#

if (heldItem is WeaponItem weapon) { sr.sprite = weapon.sprite; }

rancid tinsel
#

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

grand badger
#

It’s correct, but each SO type needs to be on its own script yes

teal viper
#

I think it's fine in the latest versions of the editor, but I'd still put them in separate files.

grand badger
#

Maybe that’s changed on recent unity versions. Try it

rancid tinsel
#

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

grand badger
#

No, it’s polymorphism

#

Yes

rancid tinsel
#

im too tired lol

grand badger
#

Inheritance is a feature that allows devs to use polymorphism

rancid tinsel
#

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?

grand badger
#

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

teal viper
grand badger
#

Polymorphism wouldn’t work if inheritance didn’t exist

rancid tinsel
#

like Attack() and Attack(bool ranged)

grand badger
#

That’s not polymorphism lol, that’s called method overloading

rancid tinsel
#

is that not part of it?

grand badger
rancid tinsel
#

damn i need to reread the material 😭

teal viper
#

It would be polymorphism if you were to override the Attack() method in an inheriting class.

rancid tinsel
#

protected override thingies

grand badger
#

Or public

rancid tinsel
#

👮

grand badger
#

Friggin’ auto correct lol

rancid tinsel
#

how does public tie into polymorphism?

teal viper
#

It doesn't. It's just an accessor modifier.

rancid tinsel
#

oh wait you mean public override right?

#

iirc it has to be the same access modifier as the method in the base class right?

grand badger
rancid tinsel
#

i only started sleeping like 2 months ago tho so might as well be

grand badger
#

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 👍

rancid tinsel
#

exciting

#

i just hope by good parts you didnt mean unit testing

teal viper
#

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.

grand badger
rancid tinsel
teal viper
grand badger
#

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

lilac dawn
#

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

grand badger
#

Why are you using a static GO btw? Curious

teal viper
teal viper
grand badger
#

Good talk :p

lilac dawn
grand badger
#

Sure? That’s not what I asked tho

#

Like why is it static in the first place?

#

the approach you described would work

lilac dawn
#

I thought Unity will combine them if I mark it as static

grand badger
#

Ahh.. no it does some optimizations for static objects but if you have specific optimization specs you might wanna handle them explicitly

rancid tinsel
#

is .Count the same as .Length but for lists?

lilac dawn
#

I see, thanks much!

grand badger
teal viper
steep rose
grand badger
#

You’ll eventually stop using arrays completely lol, so it’s fine 👍

rancid tinsel
#

im assuming this task is no different from what i just did with the items right?

#

aside from the logic part

teal viper
grand badger
rancid tinsel
#

Trap > FireTrap / WaterTrap / ElectricTrap etc

grand badger
#

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)

rancid tinsel
#

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

grand badger
#

Nice try, but google Unity OnTriggerEnter (or +2D)

rancid tinsel
#

oh yeah

#

i didnt even think of doing that

rancid tinsel
#

i got it done!

#

thanks a lot for all the help guys

#

and have a good night 🫡

cunning narwhal
teal viper
cunning narwhal
#

Not obvious to me, still having a hard time understanding SOs

teal viper
#

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.

stuck field
strong wren
cunning narwhal
teal viper
stuck field
#

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

grave bluff
#

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

grave bluff
#

I changed script execution order and it fixed it

rich adder
#

sometimes its necessary but the design could be better

grave bluff
#

but I wish there was a more robust way to do it

rich adder
#

proper dependency injecting

grave bluff
#

I looked it up and apparently the execution workslike:

obj1 Awake
obj1 OnEnable
obj2 Awake
obj2 OnEnable
#

which is inconvenient :)

grave bluff
#

who would do the dependency injecting?

rich adder
grave bluff
#

I don't know what that is

tulip pilot
#

Alright gentlemen, I have figured out how to spin a Motor

#

but now I am having big problems trying to simulate Torque and Load

spare mountain
tulip pilot
#

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

tepid summit
#

does anybody have a clue what this error means? it just randomly started showing up

north kiln
tepid summit
#

alr

#

it does seem to have stopped

tepid summit
north kiln
#

It's an exception

#

so it doesn't stop anything, it was thrown once

tepid summit
#

aight

#

ty

wooden sandal
#

i just wonder... do i even need to save the state of my serialized objects to disk?

wooden sandal
#

i mean. arent they already serialized? i just wonder because i try to save them to my json save file

#

to track progress

teal viper
eternal needle
# wooden sandal to track progress

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

wooden sandal
#

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||

teal viper
eternal needle
teal viper
#

If you want to save something between sessions, you need to implement a saving system.

wooden sandal
normal arrow
#

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);
    }```
normal arrow
#

but how do i say "look at that direction" ?

normal arrow
ripe shard
#

transform.rotation = lookat

ripe shard
rocky canyon
#

transform.forward would be forward (local space)

ripe shard
#

to look at a thing, forward = posOfThing - posOfObserver

normal arrow
#

So it's my variable direction right ?

ripe shard
#

I sus it might

languid spire
normal arrow
#

basically i have to replace "LookRotation" to "Lookat" ?

normal arrow
languid spire
normal arrow
#

why ?

languid spire
#

you should never use quaternion.eulerAngles as INPUT into any method

normal arrow
#

Okay ! Thank's !

rocky canyon
languid spire
rocky canyon
#

took u 3 seperate occasions blasting me for it

#

but finally 💪

grand badger
rocky canyon
#

gives inconsistent results

#

different values can be the same rotation..

#

gets whacked out

#

but he can probably give u a more technical reason

grand badger
#

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)

night valve
#

i dont get it why there is .eulerAngles getter in the quaternion

rocky canyon
#

u can use eulers..

#

just the right way

night valve
#

so provided the rotation is around a single axis? idk about other right ways

languid spire
#

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!

night valve
#

thats why i question the presence of said getter ;D

languid spire
#

indeed. getter for display purposes ONLY

night valve
#

display of... incorrect results? or am i missing something obvious

languid spire
#

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

grand badger
#

imo it's not the getter that's wrong architecturally.. it's how Unity handles rotation

queen adder
#

just learn some abstract algebra and use quaternions tbh

#

imo

languid spire
#

no, thats just the way Quaternions work, Unity has no control over that

night valve
rocky canyon
#

i use eulers all the time.. alot of the time they're fine..

night valve
#

(tried with constructing a rotation matrix manually then comparing to unity's rotation. Results were equal)

grand badger
#

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)

timber tide
#

all you really need is quaternion.angleaxis and quaternion.lookat

languid spire
grand badger
#

Quaternion.LookAt is bleh 😛

night valve
#

AngleAxis is all you need tbh

grand badger
timber tide
#

Ah, yeah it's LookRotation

#

then slerp to it

night valve
#

a nice learning task would be re-creating LookAt behavior by using AngleAxis only. helped me to understand how to use quaternions

grand badger
#

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

night valve
#

in fact its just 3x3*1x3 matrix multiplication (correct me if im wrong)

rocky canyon
#

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

grand badger
#

rotation is just one line in that matrix -- that transform matrix

night valve
#

ok thx

eternal needle
night valve
#

really? i may messed something up, but was pretty sure that A rows and B collums have to be the same

eternal needle
#

The numbers are the other way around, should be 3x3 and 3x1

night valve
#

righht, thanks

eternal needle
#

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

grand badger
#

or you could multiply a 1x3 with a 3x3 lol.. order matters here -- same with quaternions

bronze estuary
#

Hey guys, Microsoft Visual studio or Visual studio code. Which one is better to use with Unity?

#

!vs

eternal falconBOT
#
Visual Studio guide

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)

eternal needle
grand badger
#
q1 * q2 = (w1w2 - x1x2 - y1y2 - z1z2, 
           w1x2 + x1w2 + y1z2 - z1y2, 
           w1y2 - x1z2 + y1w2 + z1x2, 
           w1z2 + x1y2 - y1x2 + z1w2)
bronze estuary
#

Okay thanks for replying @eternal needle

grand badger
#

so (q1 * q2) != (q2 * q1)

#

yeah VS is the best C# IDE atm imo. Rider comes second and VSCode comes third

rocky canyon
#
  • RIDER
  • VS
  • VSCODE
grand badger
#

boooo

#

sponsored

rocky canyon
#

pfft, nu-uh.. i only use Rider during free-early passes 😄

night valve
#

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

rocky canyon
grand badger
#

I use Rider on my Macbook and Linux machine where actual VS isn't supported. I get frustrated every time.

rocky canyon
#

Rider is great for telling u how bad u code

grand badger
#

but gotta respect the fact that it works, lol. It's quick too

woven stump
grand badger
#

friggin' Rider code practice assumptions man

rocky canyon
#

just click the open tab to close it..

eternal needle
night valve
rocky canyon
#

wat was the other one?

grand badger
#

it literally autoformats my .AddListener(() => { return 2; }) into:

.AddListener(
              () =>
                   {
                        return 2;
                    }
              );
rocky canyon
#

ohh for the SDK u need to update that

#

Get the SDK homie

rocky canyon
#

ppl making me think its no better than notepad++ or notepad even

north kiln
grand badger
#

sadly they have lots of code practices hardcoded on their autoformatter

rocky canyon
north kiln
#

Like what? I've not seen anything you can't just set

north kiln
#

But you just change your braces style in the settings and it won't do that

#

as with any sensible IDE

rocky canyon
#

its helping u out for when u need to go in and add to that 😛

#

one liners? hell nah son

grand badger
#

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

rocky canyon
#

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

languid spire
rocky canyon
#

im done w/ it for a good month or more..

#

it broke my brain

languid spire
#

rofl

night valve
#

Um... Tower defense? :v

rocky canyon
#

anti-aircraft gun

#

no reason

night valve
#

Ye I mean making tower defense turrets should be the most basic thing to do with quaternions

languid spire
# rocky canyon

that's cheating, a tank does not have a fixed position/rotation body

rocky canyon
#

but as far as i know its all local space

#

should work fine 👍 😝

languid spire
#

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'

night valve
#

But there is no roll, only yaw an pitch. I'd say a working spaceship controller would make you a true master

languid spire
#

of course there is roll

bronze estuary
#

and I just downloaded Unity 6 preview for Junior programmer from Unity Learn.. is that okay?

languid spire
night valve
#

Oh, right. Roll of entire tank. Makes sense

rocky canyon
#

just an exercise.. was welll worth it.. b/c thats when it finally sank in about what steve had been saying about eulers

night valve
#

Predictive aiming ❤️ was it difficult to make it always hit the target?

rocky canyon
#

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

rocky canyon
#

sometimes it still misses b/c its using rigidbody projectiles

languid spire
rocky canyon
#

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

night valve
#

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

rocky canyon
#
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
rocky canyon
#

or else the turrets gonna just be wasting ammo

night valve
#

Yep

rocky canyon
#

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..

languid spire
rocky canyon
#

😅

night valve
#

Isn't that to keep things realistic, bullet should ask tower just once, right before a shot?

rocky canyon
#

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

night valve
#

I guess it's sufficient for a game ;D

rocky canyon
rocky canyon
night valve
#

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

rocky canyon
#

nah its not tied to anything prefabs for lyfe

rocky canyon
#

dont want people stealing my million dollar ideas 🙄

night valve
#

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)

languid spire
strong mica
#

Any suggestion?

languid spire
#

!code

eternal falconBOT
rocky canyon
#

how can I do the equivilent of a null check for a static class?

languid spire
rocky canyon
#

roger, looking up right now

signal cosmos
#

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?

languid spire
strong mica
languid spire
#

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

burnt vapor
rocky canyon
#

ya, just poor wording

languid spire
#

he said 'equivalent' so I guess he knows that

rocky canyon
#
    public static class Utils
    {
        //SETUP
        public static bool? IsInstalled { get; private set; } = null;

        static Utils()
        {
            IsInstalled = true;
        }```
i came up w/ this
burnt vapor
#

Oh, you mean like checking if it's initialized?

rocky canyon
#

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);```
burnt vapor
#

Why a nullable boolean, though?

#

Why not use the false value?

languid spire
#

because it looks like a null check

rocky canyon
burnt vapor
#

If you check if something is initialized there's no reason to have a third state

languid spire
#
if (Class.IsInstalled.HasValue) // initialized
else // not initialized
burnt vapor
rocky canyon
#

ya, i see your concerns.

strong mica
#
          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
rocky canyon
#

i think i got it now 👍 thanks guys

burnt vapor
burnt vapor
#

The only logical reason would be because you need a third state, but there are two

burnt vapor
#

That's a wild preference

rocky canyon
# burnt vapor 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

burnt vapor
rocky canyon
#

its just a static utilities class..

burnt vapor
#

Because you can be sure the constructor is called, so this extra check is not required

rocky canyon
#

it doesnt need to be present.. but alot of errors in my codebase specifically if its missing

rocky canyon
#

just now getting comfortable w/ properies and getters and setters and whatnot

burnt vapor
#

That's fine, just interested in seeing the reason for it

rocky canyon
languid spire
burnt vapor
#

Often a lot of code is added that would make sure the logic is solid, but often it's not required

burnt vapor
# rocky canyon

But this constructor does nothing. I would assume it sets data somehow?

strong mica
burnt vapor
#

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?

burnt vapor
#

Because it always exists. It has no instance so it can't be null

languid spire
rocky canyon
#

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

burnt vapor
#

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 atwhatcost

rocky canyon
#

@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)

burnt vapor
#

A utils class is a very good idea, that's not an issue

#

I often make a lot myself

rocky canyon
#

well, the project is made up of different pieces and stuff.. (theres a chance the static class doesn't make it into the project)

burnt vapor
#

If it didn't exist, then you would be not even be able to use it because the intellisense could not find it

rocky canyon
#

soo.. if i duplicate my project.. and delete the utils class.. ur telling me it still exists?

burnt vapor
#

For example, if it's in a different unreferenced assembly definition

burnt vapor
rocky canyon
burnt vapor
#

Also, your code would not compile

rocky canyon
north kiln
#

(to be clear, static classes are initialized when they're first accessed)

burnt vapor
#

It would not compile because it doesn't know what Utils.RealtimeDebug is

rocky canyon
#

say i wanted it to compile.. regardless if that class is ther