#💻┃code-beginner

1 messages · Page 451 of 1

mint ingot
#
public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;

    public float forwardForce = 2000f;

    public delegate void MovementFunction();
    private Dictionary<KeyCode, MovementFunction> movementFunctions;

    void Start()
    {
         movementFunctions = new Dictionary<KeyCode, MovementFunction>();
         movementFunctions[KeyCode.A] = MoveLeft;
         movementFunctions[KeyCode.D] = MoveRight;
    }

    void Update()
    {
        foreach (var keyFunctionPair in movementFunctions)
        {
            if (Input.GetKey(keyFunctionPair.Key))
            {
                keyFunctionPair.Value();
            }
        }
    }

    void MoveRight()
    {
        rb.AddForce(200,0,0);
    }
    void MoveLeft()
    {
        rb.AddForce(-200,0,0);
    }
}

y'all think this is a good way to handle movement? I'm making a begginer cube evasion game from brackeys and i thought i would have fun with input, didn't like the multiple if statements on there

opal zealot
#

I'm following a tutorial that allows me to detect clicks on a Collider Component for 2D, but I plan to use it for 3D objects. Do I need to change anything from this script?: https://hastebin.com/share/ganecuneya.csharp

#

Or can I keep it as it is without any needed conversions for 3D projects in Unity?

languid spire
mint ingot
#

so how do you recommend i do it?

languid spire
#

I just told you, and if you are going to use GPT code without checking it you are on your own

mint ingot
#

began yesterday

#

there's 2 times i call dictionary and y ou tld me to put system.action

languid spire
#

even more reason to check everything via the docs

mint ingot
#

do i put it in both?

#
private Dictionary<KeyCode, System.Action> movementFunctions;

    void Start()
    {
         movementFunctions = new Dictionary<KeyCode, System.Action>
         {
             [KeyCode.A] = MoveLeft,
             [KeyCode.D] = MoveRight
         };
    }
#

like this

languid spire
#

that should work although I dont know why you changed the structure you already had

mint ingot
#

well you told me to put System.Action and vscode suggested i simplify it to
{
[KeyCode.A] = MoveLeft,
}

languid spire
#

who is writing this code you or stupid AI's?

mint ingot
#

stupid me

languid spire
#

apparently not

mint ingot
#

so what am I doing wrong here exactly

languid spire
#

what you are doing wrong is not understanding what you are doing

mint ingot
#

yeah I got that

#

should probably read something up

#

the issue is I programmed in LUA 5+ years

#

and all the beginner shit i was doing there are following me to here

#

and im trying so hard not to lmao

languid spire
#

simple solution, for every line of code that you are not 100% sure you know exactly what it means, go read the relevant docs page

rough dust
#

So I'm trying to make a game that revolves around riding a bike. And the player has the ability to ride it and get off, but how can I look for open places to dismount the player? Like let's say the default dismount side is to the left, 1 unit out. But how can I check if there's a wall there and place the player in an open spot?

plain abyss
#

Can someone help me with code to create a search dropdown in unity which can be used as input, PS:- im new to unity

opal zealot
rough dust
# languid spire Raycast
    private bool IsAreaClear(Vector3 position, float radius)
    {
        return !Physics.CheckSphere(position, radius, interactableLayer);
    }

    public void DismountBike()
    {
        GetComponent<CharacterController>().enabled = true;
        GetComponent<CapsuleCollider>().enabled = true;
        GetComponent<PlayerMovement>().isRidingBike = false;
        GetComponent<PlayerMovement>().FadeStaminaBar(true);

        Vector3 leftPosition = bike.transform.position - bike.transform.right * 1.25f;
        Vector3 rightPosition = bike.transform.position + bike.transform.right * 1.25f;
        Vector3 frontPosition = bike.transform.position + bike.transform.forward * 2f;

        bool leftIsClear = IsAreaClear(leftPosition, 0.5f);
        bool rightIsClear = IsAreaClear(rightPosition, 0.5f);
        bool frontIsClear = IsAreaClear(frontPosition, 0.5f);

        Vector3 dismountPosition = bike.transform.position;

        if (leftIsClear)
        {
            dismountPosition = leftPosition;
        }
        else if (rightIsClear)
        {
            dismountPosition = rightPosition;
        }
        else if (frontIsClear)
        {
            dismountPosition = frontPosition;
        }

        // Move player to dismount pos and set parent to null
        transform.SetParent(null);
        StartCoroutine(SmoothDismount(dismountPosition));

        bike.GetComponent<BicycleVehicle>().enabled = false;
        bike.GetComponent<BoxCollider>().enabled = true;
        canInteract = true;
        isNearBike = false;

        // Hide interact prompt if it's showing
        ShowPrompt(false);
    }

This is what I've got, but even when there's a wall to my left it phased me into or through the wall

brave veldt
#

I've got a slider that changes value with a controller stick input - left to decrease, right to increase. This happens using UnityEvents and the OnValueChanged event; however, I need the slider to wrap/loop values around when you increase the value at maxvalue, and when you decrease the value and minvalue. It's being a real PITA! Does anybody have any thoughts on how I should approach this?

I could try and write something from scratch, but I don't want to break away from the UnityEvent system because I've got a fairly complicated local-multiplayer controller setup in the scene.

#

the main issue is that you can't just check if the value is > than maxvalue or < minvalue because the slider won't let you go higher or lower than the min/max

languid spire
languid spire
brave veldt
#

I'd probably have to have a check in there to see if currValue is less or greater than changeValue? because i would have to subtract

languid spire
brave veldt
#

Yeah the larger slider value is something I've tried, but because it's attached to an array of gameobjects it throws null reference. I can probably figure something out though. that does seem like the easiest although also hackiest method

languid spire
#

problem is that slider only reports the new value rather than the changeValue and once you reach the slider min/max it wont report at all, so then you need to allow it to go 'out of bounds'

brave veldt
#

yeah exactly.

#

I think I may have a solution after talking with you. increasing the min/max value, and adding a check for the array of gameobjects - so it doesn't reference it if the index is the new min/max values.

tiny plaza
#

hey does this become false if the conditions are not met? (sorry idk how to explain it without the screenshot)

languid spire
#

sounds like you are using the slider value as an index so I would do
slider.min = -1
slider.max = array.Length

OnValueChanged(int value)
if (value < 0) value = array.Length-1;
if (value == array.Length) value = 0;
slider.Set(value, false);

brave veldt
#

cheers, that's basically what I've got. Just trying to hammer out the null references now. thanks!

languid spire
tiny plaza
short hazel
languid spire
#

trouble is if canWalk is true using && will always return true

tiny plaza
short hazel
#

No, it's &&, not ||

#

With OR it won't check the right operand if the left one is true, with AND it's the inverse

languid spire
#

of course, silly me, brain not firing on all cylinders

tiny plaza
#

so the most efficient is && ? (sorry my brain is having a hard time after an all nighter of c#)

languid spire
#

yes, if canWalk is false the return will be false, if canWalk is true the return will depend on the result of the second check

tiny plaza
languid spire
#

np, that's what we are here for

wide raven
#

I use IsPointerOverGameObject

teal viper
#

What makes it "stuck" in your code?

wide raven
#

it spam clicks

#

infinitely

quick fractal
#

Bit of a simple question but the Unity docs were confusing, if I start a coroutine with WaitForSeconds(3) in it, and call StopCoroutine(), will it stop the countdown and shut the coroutine off or will it continue?

#

I assume (and hope) it would just stop where it is and cancel the whole thing but coroutines are weird.

teal viper
languid spire
quick fractal
#

Or did you mean something else?

languid spire
#

the waitforseconds will expire but then stop

quick fractal
#

Alright great, thank you!

hot lily
#

I'm pretty much running out of ideas how to use the cinemachine camera properly as a 3rd person camera

#

currently if I turn my mouse around, there will be a delay before the camera changes its rotation such that the playable character is centered

#

I can turn off the dampening and have it be perfectly centered, but then I lose out stuff like having the character zoom out of screen

wet bobcat
#

I want to get Object Rotation XYZ values as shown in the Inspector sent over OSC/UDP to another application (PureData). My problem is that neither using Euler Angles like this:

`message.address = "/" + gameObject.tag + "/" + gameObject.name + "/EulerXYZ";

    message.values.Add(transform.rotation.eulerAngles.x);
    message.values.Add(transform.rotation.eulerAngles.y);
    message.values.Add(transform.rotation.eulerAngles.z);

    osc.Send(message);`

...or using "quaternion" values like this:

`message = new OscMessage();

    message.address = "/" + gameObject.tag + "/" + gameObject.name + "/QuatXYZW"; //here W was wrongly omitted since it was treated as Euler Angles  

    message.values.Add(transform.rotation.x);
    message.values.Add(transform.rotation.y);
    message.values.Add(transform.rotation.z);
    message.values.Add(transform.rotation.w);

    osc.Send(message);`

The first option sends values 0-360, but they are all modified when x value is changed.

The second gives gives a float between -1 and 1, but it changes direction once it hits -1 or 1.

I am sure there is a good reason for this but how can I adjust the messages to fit my purpose: Get a value 0-360 for xyz for an object depending on where it is facing? Is there another variable to acess from Unity script engine. Or could I make some kind of equation to translate the values?

The player drags objects with the mouse so I think it will be complicated to store the values in the script beforehand, like in this example:
https://docs.unity3d.com/ScriptReference/Transform-eulerAngles.html
but I am note sure.

Plz help, I need this to work to get further on...

languid spire
plain abyss
#

can someone please guide me on how to fix this so that my text is visible

languid spire
#

Assign a TMP Font

plain abyss
languid spire
plain abyss
#

someone please guide me on if there a way i can use code to set the location of the triangle(target) and circle(player) to either of the squares(LOC1 and LOC2)

plain abyss
ivory bobcat
#

What do you want to happen?

languid spire
eternal falconBOT
#

:teacher: Unity Learn ↗

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

ivory bobcat
#

I'm assuming you're wanting an object to teleport to another.

plain abyss
languid spire
plain abyss
languid spire
wet bobcat
languid spire
eager spindle
eager spindle
#

no

#

what do you need help with

uncut wolf
#

understandable have a great day

wet bobcat
languid spire
wet bobcat
languid spire
#

sure, all transforms have a forward direction

eager spindle
#

theres transform forward, transform up and transform right

#

and a lot of other helpful stuff

wet bobcat
languid spire
wet bobcat
wet bobcat
eager spindle
#

idk about it not returning current values

tender wharf
#

gamers, all of my sprites are extremely tiny, i have no clue how to fix

#

well ig scaling fixes them but idk that sounds wrong

eager spindle
#

when using a Sprite renderer, the size of the sprite in the world depend on the actual size of the image.
e.g. if you have a 1000x1000 px image itll be larger than a 100x100 image. you can change this in the image export settings

#

pixels per unit

#

to make a 1000x1000x image the same size as a 100x100 image in a sprite renderer, make sure the pixels per unit on the 1000x1000 image is 1000

tender wharf
#

okay so the png in question is 2048 x 2048

#

I've already tried playing with pixels per unit, but even if i put some absurd value it remains extremely tiny

eager spindle
#

if its tiny its probably cause it's not cropped properly

#

the empty space around the image will also get taken into account

tender wharf
#

wait

#

decreasing ppu started increasing the sprite

eager spindle
#

well yes that's correct but you should probably address the fact that your image might not be cropped correctly

short hazel
#

PPU: number of pixels in the sprite that must fit within 1 Unity unit (1 meter) in the scene.
If you have a 16x16px image that you want to fit in one square (think Minecraft textures where 1 block is 16x16), set the PPU to 16

warm raptor
#

hello ! How can I destroy the particule effect when it finish playing ?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Grenade : MonoBehaviour
{

    [SerializeField] private AudioClip GrenadeSound;
    [SerializeField] private GameObject ExplosionEffect;
    [SerializeField] private float FuseTimer = 4f;
    private float CurrentTime;

    void Start()
    {
        CurrentTime = 0f;
    }

    void Update()
    {
        CurrentTime += Time.deltaTime;

        if (CurrentTime >= FuseTimer)
        {
            AudioSource.PlayClipAtPoint(GrenadeSound, transform.position);
            Instantiate(ExplosionEffect, transform.position, transform.rotation);
            Destroy(gameObject);
        }
    }
}
short hazel
vestal adder
#

i dont get the point of read only properties because it says that they are for exposing a value to other scripts without letting the other scripts modify it but you could just not modify it with other scripts

wintry quarry
#

or another developer who doesn't know you're not supposed to modify it might modify it

vestal adder
#

okay i see

#

is there some way that you can accidentally modify it

wintry quarry
#

One good example is List.Count

#

you wouldn't want to modify List.Count by accident

#

but adding elements with .Add or removing elements with .Remove will modify the count properly

#

If you were able to directly modify the Count property then it could get out of sync with the number of elements actually in the list, which could be really bad.

wintry quarry
formal sable
#

Hey guys! What's going on? I think I will come back here very often 🙂

So... There is a problem. I activate the notes lying on the floor. The first note is fine with it, I close it by clicking on the button, and as soon as I open the other two notes, they close with a space, and I don't know how to remove it

slender nymph
#

show code

steep rose
#

we will need to see code then

queen adder
#

Hi chat, I'm a very beginner here, may I ask the difference between the line:

  • "if (Input.GetKeyDown ("a")) { "
  • "if (Input.GetKey (KeyCode.A)) {"
  • "if (Input.GetKeyUp (myKey)) {"
slender nymph
#

how big is the collider? because you close it in OnTriggerExit

formal sable
#

like cube

ivory breach
#

How do I make my enemy plane rotate towards the smaller plane by z axis only to rotate it like this?

formal sable
# formal sable

but it's not a trigger, it's an action when I close the note

#

a error occurs during this action

slender nymph
#

if you have an error then you need to actually say that. and provide details about the error

#

don't just expect everyone to read your mind and instantly know you have some error you've not shown or mentioned

polar acorn
formal sable
slender nymph
#

and i will say again that you are closing the note in OnTriggerExit. so if the player exits the trigger when it jumps then it will close the note

queen adder
formal sable
slender nymph
#

put some logs in your code to find out what is actually happening

formal sable
#

Okay... Wait a minute

sour linden
#

Hey,
I'm trying to access a Script from another namespace but Unity doesn't recognize neither the namespace nor the class I'm trying to get a reference to. They both are monobehaviours and attached to gameobjects, so they both do exist and work but why doesn't unity recogniye the one namespace in the other? Here are the class and the method where I want to reference the class.
Thanks for any help ^^

slender nymph
#

that's not a useful log

polar acorn
sour linden
#

Thank you. I'll take a look

formal sable
slender nymph
#

how about literally anything useful being logged

#

you are hyperfocused on this being an issue with the spacebar somehow, but your code literally has nothing to do with the spacebar, it just happens that the spacebar is making the player leave the trigger area

formal sable
#

I'll report this way...

As I said, during the reading, no keys react. While reading, I specifically pressed the space bar to make it clear that I was pressing this key.

Further, while reading the second note, I also pressed the space bar, this time the note disappeared, the character jumped, and also this jump was not counted in the console

#

yes, I'm hyperfocused on the space bar, because the other keys don't react in any way, but the space bar itself reacts and it's unclear why.

I can also send the traffic code if necessary.

summer stump
#

Why not just log something useful?
Ignore the space bar for now

slender nymph
formal sable
slender nymph
#

logging the phrase "space bar active" when you press the spacebar is not useful here at all. it's already fucking obvious you are pressing the spacebar. you need to log what is actually happening in the code that is causing it to close the fucking note

summer stump
#

Logging values, in multiple places, especially OnTriggerExit

slender nymph
# formal sable How?

why don't you spend more than half a second thinking about what i've already told you and then think about where logs might be useful in your code

tender wharf
#

so i'm using a camera for my minimap, set the camera only to show the "Road" layer

#

now is it possible to make gray area transparent

slender nymph
#

this is a code channel

tender wharf
#

nvm, i found out im dumb, you just need to set clear flags to solid color

sour linden
outer cloak
#

I need help with an error

cosmic dagger
outer cloak
#

I keep getting a message that says “gradle build failed” and when I go to the console it says pb_mesh-142988 clone mesh must have at least one non degenerate triangle to be a valid mesh collider

#

I watched a ton of YouTube videos

#

None worked

fickle plume
#

@outer cloak don't cross-post. Pick one channel.

outer cloak
#

ok

ivory breach
#

This is the script I'm using for the enemy's rotation (and movement)

wintry quarry
#

the problem is that your renderer is not laid out properly on the object

#

Show your airplane object, selected, in scene view, with the Tool Handle Rotation set to "local"

wintry quarry
ivory breach
wintry quarry
ivory breach
wintry quarry
#

The blue arrow should be facing forward. The yellow arrow up, the red arrow to the right

#

See how you have it with yellow forward and blue down?

#

GIven the direction of the arrows, the code is working perfectly

#

you have to just fix your object here

#

the best way to do that is to go back into Blender and re-export the model with the proper settings/rotation for Unity

ivory breach
wintry quarry
rich adder
#

at least now it looks at your player correctly lol

ivory breach
#

I want the plane to look at the player in one axis only, like in this picture

wintry quarry
#

ok well that's a totally different/new question

cosmic dagger
#

that's not the same thing you asked before . . .

ivory breach
#

Wdym?

wintry quarry
#

you want thje top of the plane to always face the camera?

wintry quarry
rich adder
ivory breach
#

Sorry, I just wanted to know how I can make the enemy look at the player in one axis without affecting the others

wintry quarry
#

you'll want to do var rotation = Quaternion.LookRotation(heading, Vector3.back); if I understand your question correctly.

ivory breach
#

In this case, x axis

wintry quarry
#

this looks more like y axis

wintry quarry
#

it's rotating on its own y axis

ivory breach
wintry quarry
#

Euler angles are not unique

ivory breach
#

I see

#

Alright, your answer DID work, but I would like to know more on what Vector3.back did to rotate the plane like that

wintry quarry
#

It's the "up" direction of the resulting rotation

#

You wanted the Up direction to always be facing at (0, 0, -1) world direction which is what Vector3.back is

#

so we're just creating a rotation where forward is heading and up is (0, 0, -1)

#

which is what you asked for

#

if you don't provide an up parameter to LookRotation (as you had originally) it defaults to the world up direction

#

hence your plane doing the things it was doing before, keeping the top of the plane upwards.

ivory breach
#

I should experiment with the parameters to learn more about LookRotation

wintry quarry
#

sure

#

you can think of it this way

#

when you want an object to look at something, there's still 360 degrees of freedom where you can look at the thing but still roll around (like a bullet rolling as it flies forward)

#

the "up" parameter locks in which angle in that 360 degress of freedom to use.

ivory breach
#

Noted

queen adder
#

this is a pretty minor issue i understand. However when i am using the unity editor i notice it is lower fps than normal, compared to other windows on my pc. For exmple moving my mouse around feels like its 60 fps instead of the 160 it should be. Is there a way to uncap the fps?

rich adder
queen adder
#

it just "feels" like it. If there is a way to show the numbers lemme know

rich adder
#

profiler and such

#

"feels" is not a realistic measurement lol

#

you have to know why

queen adder
#

ok i understand

#

my editor is capped at 33 fps i think

#

according to profiler

harsh dew
#

Okay so i have a box collider which starts an audiosource, now i want to have subtitles showing up in your screen, i have a script and put the textmeshprougui in but its not showing for some reason

#

this is the script for the subtitlemanager

using System.Collections;
using UnityEngine;
using TMPro;

public class SubtitleManager : MonoBehaviour
{
public TextMeshProUGUI subtitleText;
public AudioSource audioSource;
private bool hasPlayed = false;

private void Start()
{
    subtitleText.text = "";
}

private void OnTriggerEnter(Collider other)
{
    Debug.Log("Trigger entered by: " + other.name);
    if (other.CompareTag("Player") && !hasPlayed)
    {
        StartCoroutine(PlayAudioWithSubtitles());
        hasPlayed = true;
    }
}

private IEnumerator PlayAudioWithSubtitles()
{
    audioSource.Play();
    Debug.Log("Playing audio");

    yield return ShowSubtitle("What happened?", 0, 2);
    yield return ShowSubtitle("Where is everybody?", 2, 2);
    yield return ShowSubtitle("Mom? Dad?", 4, 2);
    ShowSubtitle("", 6, 0); // Leeg maken van de ondertitels
}

private IEnumerator ShowSubtitle(string text, float startTime, float duration)
{
    Debug.Log($"Showing subtitle: {text} after {startTime} seconds for {duration} seconds");
    yield return new WaitForSeconds(startTime);
    subtitleText.text = text;
    Debug.Log("Subtitle text set to: " + text);
    yield return new WaitForSeconds(duration);
    subtitleText.text = "";
}

}

eternal falconBOT
harsh dew
#

huh?

wintry quarry
#

How to share code on this discord. Read it

harsh dew
#

excuse me for that

#

yo its not working

#

how does that work?

#

i read ut but i dont understand any of it

rich adder
harsh dew
#

ooh okay

#

is this good

rough hill
#

The InventoryPanel is assigned in editor but it still plays the error message. Anyone knows what I am doing wrong?

rich adder
# harsh dew is this good

so what is it exactly thats supposed to happen with subtitles?
what is working vs whats not working, are the logs you put printing ?

rich adder
slender nymph
harsh dew
rich adder
#

you have a bunch of logs, thats good step in right direction. But did you check them in the console ?

rough hill
harsh dew
#

The only thing i have is The referenced script (Unknown) on this Behaviour is missing!
but thats for the audioTrigger

rich adder
harsh dew
rich adder
#

you said the audio plays?..

#

can you screenshot your console in its entirety

#

not even Debug.Log("Trigger entered by: " + other.name); is printing?
either you have logs hidden or the trigger i s never happening

harsh dew
rough hill
#

Cant assign the InventoryMenu here on my prefab Itemslot.

wintry quarry
rich adder
# harsh dew

would be nice to know when you took this..is this during playmode when you walk into trigger?

harsh dew
#

that error is from 10 minutes ago

rich adder
harsh dew
#

oh wait now i see it, that error occured when i put the audio into the SubtitleManager script

rich adder
#

its also possible you just made changes to script during playmode and saved

#

that still is unrelated to what you're trying to debug though..

charred igloo
#

are variables attached to scripts or gameobject with the script?
if a script is attached to more than one script will a variable change for every script or only the one that meets the conditions that make the variable change?

cosmic dagger
rich adder
cosmic dagger
rocky canyon
polar acorn
cosmic dagger
charred igloo
#

mhh, but if i do something like

if(getComponent<BoxCollider2D>().enabled == false)
{
Debug.Log(“works”);
}

it only works if all colliders are disabled. pls help

cosmic dagger
polar acorn
#

It'll get a BoxCollider2D from this object

cosmic dagger
cosmic quail
#

do you have multiple colliders on the same gameobject?

cosmic dagger
#

You have to provide more information . . .

charred igloo
#

i know im sorry im trying to figure out how to tell

#

i want to check if only the collider in the same gameobject as the script is disabled

#

but i have the same scripts in multiple gameobjects, and every gameobject has a collider

polar acorn
charred igloo
rocky canyon
#

🤔 sounds like a set-up issue

polar acorn
#

So, when does this code run?

charred igloo
#

oh im so sorry

#

it was a setup issue

#

thanks for the help tho

tender wharf
#

is this cursed for displaying players positions on a minimap xd

winter tinsel
#

how would i change the value of a slider?

#

float to slider ig

slender nymph
#

what did google say

rich adder
languid spire
#

better slider.Set(value, false)

winter tinsel
#

whats the point of the false?

languid spire
#

so you dont get the onvaluechanged callback

winter tinsel
#

wait huh

#

unaccessable due to its protection level

#

what

wintry quarry
#

Again, check the docs for available functions and properties

slender nymph
#

Set is protected, you'd have to use SetValueWithoutNotify

winter tinsel
#

cuz i see theres float and input

#

whast the input about

slender nymph
#

if you are not sure how method parameters work, then perhaps you should start simpler with the beginner courses pinned in this channel

winter tinsel
#

i know how it works im just confused as to what to put as the input?

#

sofar ive only encountered values

slender nymph
winter tinsel
#

wait im stupid nvm

#

yet the slider wont move

#

even though the value changes it doesnt affect the value of the slider

runic urchin
#

hey, i was just wondering if anyone could tell me how i could change the layer of a game object using code? i want it to change after i press left click and im having a tough time with it lol

rich adder
winter tinsel
#

what

#

ingame it doesnt change yeah

runic urchin
wintry quarry
winter tinsel
runic urchin
wintry quarry
#

pay attention to the types of things

#

As you can see layer is an int

#

you need to put an int there

#

the default layer is 0 IIRC
so just myObject.layer = 0;

runic urchin
rich adder
wintry quarry
slender nymph
eternal falconBOT
runic urchin
slender nymph
wintry quarry
runic urchin
slender nymph
#

it's a good thing that the bot's embed directly below my message makes what i'm referring to more clear

runic urchin
wintry quarry
#

You can use Debug.Log to do that

#

and yes you should think carefullyt abouit where you want to put that code

rugged loom
nova shore
#

wanted to make it so that moving your mouse horizontally would make it rotate around the character(rb)
and vertically would it make it just go up n down for now also while keeping the centre of fov at the char.

it just aint workin as intended. the rotation in x-z plane is fine, but it doesnt move with the character meaning its pivot is the origin
and with cam.TransformDirection it spazzes out like crazy

Angle += dx * mouseSens;

cam.position =  cam.TransformDirection(new Vector3(Mathf.Sin(Angle)
    , 0, -1 * Mathf.Cos(Angle)) * CamDist);
cam.position += new Vector3(0, dy * -mouseSens, 0);
cam.LookAt(rb.position);
wintry quarry
queen adder
#

why does the top one work but not the bottom one if (_camBottom.y < 0) { Debug.Log("Bottom: " + _camBottom.y); transform.Translate(Vector3.up * _verticalInput * _speed * Time.deltaTime); } else if (_camTop.y > 1) { Debug.Log("Top: " + _camTop.y); transform.Translate(Vector3.down * _verticalInput * _speed * Time.deltaTime); } basically what I am trying to do is reverse the direction so when they hit the barrier they can't go up anymore but they can go down if they want and vice versa

wintry quarry
winter tinsel
winter tinsel
winter tinsel
nova shore
wintry quarry
#

and then just rotate the pivot

slender nymph
wintry quarry
#

you can test it in the editor

winter tinsel
slender nymph
#

put this line directly after the SetValueWithoutNotify call and show what it prints: Debug.Log($"{staminaUI.name} ({staminaUI.GetInstanceID()}) value set to {staminaUI.value} from {name} ({GetInstanceID()}) and value {stamina}", staminaUI);

nova shore
winter tinsel
polar acorn
slender nymph
#

yes that is where it is supposed to be . . .
it just has to be after the SetValueWIthoutNotify call

winter tinsel
#

okay its printed something

polar acorn
# winter tinsel

Now, click once on that log. It should highlight an object in the hierarchy. Show that object's inspector

winter tinsel
#

it highlighted the slider

#

what am i looking for

polar acorn
#

Show the inspector of it

slender nymph
#

i'm curious why the player object has a positive instance id 🤔
does whatever is calling your staminaBar method happen to have a reference to the player prefab rather than the player instance in the scene?

winter tinsel
#

theres no player prefab

#

on the second pic if i make it have no function the slider moves if i change the value anually in the inspector, otherwise its stuck, if i try to slide it it wont work

polar acorn
slender nymph
#

congrats, you are most likely just constantly calling that staminabar method

winter tinsel
#

issue is "stamina" changes

#

as a value, but it wont change the value ??

#

it wont change the slider value

slender nymph
#

prove it because the log showed it was being set correctly

#

what invokes that unity event you've screenshot anyway?

winter tinsel
polar acorn
winter tinsel
slender nymph
winter tinsel
#

it does

polar acorn
#

and that's what the inspector says it's at

winter tinsel
polar acorn
slender nymph
# winter tinsel ive debugged it

"i'Ve dEbUgGeD It"
so fucking show that. when i asked you to prove that the value actually fucking changes, then i expected you to show me the actual proof that it changes.

polar acorn
#

According to the information you have provided, stamina is 5 and the slider shows 5. If you're seeing something that says otherwise, you need to show that

#

Because right now it appears to be doing exactly what you want it to do

polar acorn
winter tinsel
#

no

polar acorn
#

Then it literally does not matter

winter tinsel
#

what

polar acorn
#

At the time you're calling the function to change the slider, stamina is 5. So you set the slider to 5

winter tinsel
#

im stupid

#

its not in update()

#

thats why

#

but otherwise how do i add it to the functions????

#

i cant make it public within update

slender nymph
#

hey remember when i asked what was invoking that unity event that calls the staminabar method and you just completely ignored that question?

winter tinsel
#

i should take my own advice and go to sleep

slender nymph
polar acorn
winter tinsel
#

red underline

polar acorn
#

Show !code, show error

eternal falconBOT
winter tinsel
#

if i put it in update

polar acorn
wintry quarry
winter tinsel
#

im gonna go to sleep

winter tinsel
#

let me count em

#

10 hours on the road and i havent slept since 6 so

#

definitely has some effect

#

but it works

#

i just put the function in the sprint code

#

apologies for wasting time

crisp prism
#

Im instantiate two obstacles and two spawn but it only detects one leaving

wintry quarry
#

you should put a log outside your if statement

#

and print all those values you're checking in the if statement

#

but seems clearish to me...

#
hasSpawned = true; // Prevent multiple spawns```
```cs
&& !hasSpawned &&```
#

you're explicitly setting this variable true... and explicitly checking that very same variable

crisp prism
#

i put it outside the if and its still only detecting one leaving

wintry quarry
#

and isn't that the point, to prevent multiple spanws?

crisp prism
#

its detecting two in the on trigger

#

yea

#

it does prevent multiple spawns

wintry quarry
crisp prism
#

yea

#

just for some reason then doesnt detect two leaving

wintry quarry
#

show your console?

crisp prism
#

ill send a picture

wintry quarry
#

and show the new code with the moved log?

crisp prism
#

there is double touched the plane then left because its not detecting that two left only one

#

so one stays behind

wintry quarry
#

I don't see Player left the plane at all

#

if that's what you mean

crisp prism
#

player isnt relavent

wintry quarry
#

well I see 22 and 9

crisp prism
#

yea

wintry quarry
#

so hard to say what's going on there at all

crisp prism
#

thats the problem

#

its just weird the trigger is debugging that 2 touch it but only one is exiting

wintry quarry
#

What are these obstacles? How do they work? What are they doing?

#

What's the goal here

#

maybe 13 of the 22 are still inside

crisp prism
#

its and endless runner I have the platform and player constantly move along the z axis and the player can move the capsule just left and right, the obstacles spawn and when they leave the plane it activates the trigger exit and respawns them infront of the player

#

for and almost endless loop of obstacles

#

problem is its not deleting both obstacles that leave and its leaving one behind

wintry quarry
#

which object has this script

crisp prism
#

the plane controls the object spawn

#

I have a prefab for the obstacles

#

public GameObject Obstacle;

#

it pulls it from there in the plane script to create it

wintry quarry
#

and where di you put the new log

crisp prism
#

outside the if in the trigger exit

#

still only detecting one leaving for some reason

#

wait

#

your right

#

I moved the wrong debug

#

when i move the debug outside the if method for trigger exit it prints two leaving

wintry quarry
#

yes

crisp prism
#

so its something with the if

wintry quarry
#

so it's working fine

#

I'm not sure i understand the point of this hasSpawned variable

crisp prism
#

the debug is fine its just still not deleting both in the trigger exit

wintry quarry
#

seems like it prevents it from ever handling more than one exiting obstacle

#

yeah because of hasSpawned

#

it's unclear what the intent of that is

crisp prism
#

its supposed to prevent more than two obstacles from spawning, since it spawns based on when they leave then it exponetially when start spawning them

#

is the idea

#

if i dont limit it

wintry quarry
#

so it's working exactly as you designed it

#

You need a better system for determining when to spawn things to be perfectly honest

#

it shouldn't be tied to when an object is exiting at all imo

crisp prism
#

yea im very new to the whole coding thing

#

kind of the only idea I could think of for and "endless runner"

#

dont know how else to detect them passing the screen

#

then to spawn new ones

wintry quarry
#

I don't see why those two things need to be related at all @crisp prism

#

you can start with something simple like spawning one obstacle per second:

float timer = 0;
public float interval = 1;

void Update() {
  timer += Time.deltaTime;
  if (timer > interval) {
    timer -= interval;
    SpawnACube();
  }
}```
#

Then you can reduce the interval over time

misty pecan
#

Im making a learn to fly clone and im wondering whether its better to actually move the player when hes flying or move the environment backwards? Which is more logical?

crisp prism
#

will keep that in mind @wintry quarry thank you for the help

#

yea but when I remove the has spawned logic everytime they spawn they double

#

so 2 - 4 - 8 - 16

#

only problem left

wintry quarry
#

you're spawning obstacles in response to old obstacles leaving

#

there's no need for that to be the case.
and you're doing two for every one that leaves.

mystic citrus
#

Does anyone know why my character flips back and forth in the x axis when he moves into a wall? Here is my flip code

//  private void Flip()
    {
        if (isFacingRight && rb.velocity.x < 0f || !isFacingRight && rb.velocity.x > 0f)
        {
            Vector3 localScale = transform.localScale;
            localScale.x *= -1;
            transform.localScale = localScale;
            isFacingRight = !isFacingRight;

            Vector3 currentScale = bulletPanel.transform.localScale;
            currentScale.x *= -1;
            bulletPanel.transform.localScale = currentScale;
        }
    }
#

Also I know it probably has to do with the velocity going back and forth between positive and negative and never being 0, but how can I 0 it or rewrite the code so that it doesnt do that?

wintry quarry
mystic citrus
#

Like I said, I know what the issue is, I just dont know how to implement it

#

Thats why Im asking

wintry quarry
#

what do you mean you know what the issue is

wintry quarry
#

you said "probably"

#

beut I don't see anything changing the velocity

#

so how can you be sure

mystic citrus
#

Because I use add force and when you hit a wall with add force it just bounces you back

#

I debugged and I know the issue

wintry quarry
#

but you're not hitting a wall after you bounce

#

so why would the velocity change again

mystic citrus
#

When I hold into the direcion of the wall, force is applied towards the wall, but the way unity does force it also makes the player bounce away from the wall with any remaining force applied to the wall, how can I make it so that the character doesn't flip when this happens

rocky canyon
#

Constrain its rotations is 1 way

mystic citrus
#

How can I do this?

rocky canyon
#

in the rigidbody component

wintry quarry
rocky canyon
#

i might be misunderstanding flip

mystic citrus
rocky canyon
#

but yea, u can reduce the bounciness for sure

mystic citrus
wintry quarry
#

I'm not sure I understand really if you're trying to fix the bounce or the fact that it flips instantly

wintry quarry
#

Because it sounds like the flip code is working perfectly, and your problem is the bounce

rocky canyon
ancient holly
#

adding a little value instead of 0 for if checks might work

#

but it would make the thing not immediate

#

i'd recommend basing it on input and velocity at the same time

warm raptor
#

Hello, is their a way to show the render / image of a camera onto a mesh like a circle, like if it was a screen ?

wintry quarry
#

Make a material - assign the texture as the render texture

#

and make your camera render to the texture

warm raptor
lost basin
#

I have a randomly generated mesh, how do I add a mesh Collider that fits the mesh at the start of the scene through a script?

#

If anyone wants to help pls pm me, I'm eeping rn and woke up bc of having a nightmare bc of this

languid spire
#

and dont forget to add it to the MeshFilter as well

wintry quarry
#

MeshFilter would be for rendering (along with a MeshRenderer)

languid spire
#

yes, I just guessing he wants to do that as well

languid spire
#

no

mint remnant
#

Windows 8.1 really?

raw token
#

I like the 3 gigs of memory, myself

crisp prism
#

@wintry quarry

#

fixed the code without the timer will add the timer later though

#
using UnityEngine;

public class ObstacleSpawn : MonoBehaviour
{
    public GameObject Obstacle; // Prefab to be instantiated as obstacles

    private bool hasSpawned; // Flag to control obstacle spawning

    void Start()
    {
        SpawnObstacle(); // Initial obstacle spawn
    }

    // Called when another collider enters the trigger collider attached to the object
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject != this.gameObject)
        {
            Debug.Log($"{other.gameObject.name} touched the plane.");
            hasSpawned = true; // Allow obstacles to be spawned again
        }
    }

    // Called when another collider exits the trigger collider attached to the object
    void OnTriggerExit(Collider other)
    {
        Debug.Log($"{other.gameObject.name} left the plane. Spawning obstacles.");

        // Destroy the exiting obstacle
        Destroy(other.gameObject);

        if (other.gameObject != this.gameObject && hasSpawned)
        {
            hasSpawned = false; // Prevent multiple spawns

            // Spawn new obstacles
            SpawnObstacle();
        }
    }

    // Spawns two obstacles at random positions
    void SpawnObstacle()
    {
        Vector3 spawnPosition1 = new Vector3(Random.Range(-4f, 0f), transform.position.y + 2f, transform.position.z + 5f);
        Vector3 spawnPosition2 = new Vector3(Random.Range(0f, 4f), transform.position.y + 2f, transform.position.z + 5f);

        Instantiate(Obstacle, spawnPosition1, Quaternion.identity);
        Instantiate(Obstacle, spawnPosition2, Quaternion.identity);
    }
}
#

now deletes and recongnizes both leaving

#

just changed up the has spawned variable placement

raw token
#

There is no off topic channel on this server

polar acorn
#

<@&502884371011731486> problem child

crisp prism
#

is this satire @lofty valley

raw token
#

a poor effort at it, anyway

languid spire
#

rofl, you have no clue whatsoever

polar acorn
languid spire
#

yes, you ddos's yourself

#

no, you idiot, 127.0.0.1 is your internal ip address

polar acorn
#

Oh my god steve please stop encouraging him

#

this is an obvious bait and you're falling for it hook line and sinker

gloomy kelp
polar acorn
gloomy kelp
polar acorn
# gloomy kelp

Show the full text of that first stack trace, in the window below this.

languid spire
#

@lofty valley Do NOT DM people without their permission

polar acorn
# gloomy kelp this?

Yeah, scroll through it and see if there's anything in there that says it's got an error of any sort

frosty hound
#

!ban 361553006774190080 Spam

eternal falconBOT
#

dynoSuccess spoi0101 was banned.

crisp prism
#

dang

warm raptor
wintry quarry
queen adder
#

Invoke only runs the method one time right>

queen adder
#

okay thats what I thought thanks i got a loop something is wrong with it then

crisp prism
#

uh @warm raptor is that beginner code

#

looks way more complicated from my beginner code

polar acorn
gloomy kelp
polar acorn
eternal falconBOT
warm raptor
eternal falconBOT
queen adder
warm raptor
polar acorn
# gloomy kelp !code

That's not how that works, but I do see one failed:

> Task :launcher:checkReleaseAarMetadata FAILED

Not entirely sure what that means, seems to be something mobile related. Maybe #📱┃mobile knows more about this

gloomy kelp
wintry quarry
warm raptor
wintry quarry
#

it may also be due to the UVs of the model you're drawing this on

warm raptor
warm raptor
ionic zephyr
#

How can I make sure that if in my inventory UI I place an object in a determined slot of the UI, then in my overworld UI it stays in the same slot??

#

Even if they are different UIs

#

which mean different slots really

wintry quarry
#

that both the inventory UI and the overworld UI read from

#

Use the MVC pattern and the observer pattern.

#

The inventory data itself would be the model
The two UIs are views

ionic zephyr
#

Let me show it graphically

queen adder
#

would anyone help me with the script I'm using for a button?

The button itself is a model with a configurable joint component and it has constraints, all that.

The button is pushed down by a collider in vr, and it's supposed to hit a trigger that triggers a script. I don't even know if the script works, I copied it from a vr button tutorial and I did everything the person said.

In the script the only thing I changed was this tag name. The button model has the tag. But being pushed nothing happens.

ionic zephyr
#

The second step involves one of the UI slots informing the Underlaying data the place in which the object has been dropped

wintry quarry
# ionic zephyr

well there's a few ways to do it but basically the UI should be listening for events from the inventory

#

one of the events could be like:

public delegate void InventoryChangedHandler(int slotId, Item oldItem, Item newItem);
public event InventoryChangedHandler OnItemChanged;```
#

something like this

#

so the inventory announces that slot 3 changed, the old item was "empty" and the new item is "health potion" for example

raw token
# queen adder

Share the script via one of the !code paste sites listed below 👇

eternal falconBOT
ionic zephyr
wintry quarry
#

Well ideally the index of the slot in the ui array and the slot number in the underlying data match up

#

so you don't have to do any conversion

#

anyway I gotta go get ready for something 👋

ionic zephyr
raw token
# queen adder what does this do?

Code in screenshots is hard to read. In that particular screenshot, doubly so because there's no syntax highlighting. If anyone wants to make a suggestion to alter your code or reference your identifiers, then they also need to transcribe the relevant portion of your code from the image by hand.

The Discord text file embed thingy also sucks on mobile and prevents you from having it up alongside Discord, unless you download the file.

So sharing large blocks of code via a paste site just makes everyone's life easier. The only time code in a screenshot is really appropriate is if you're displaying something which is happening within the IDE

queen adder
raw token
# queen adder yay

So those Debug.Log()s aren't ever getting printed to console?

And the object which this script is attached to has a collider with isTrigger checked?

queen adder
#

ye the trigger is this cube

languid spire
raw token
queen adder
#

buttonpanel is the rigid body

#

when I move the trigger cube nothing happens still

languid spire
#

Ok debugging 101
Add debug.log to prove the code is actually running
Add debug.logs to show if the Trigger methods are being entered

rocky canyon
queen adder
#

does it need one?

raw token
# queen adder when I move the trigger cube nothing happens still

For a physics message like OnTriggerEnter() to occur, both of the objects involved in the collision need a collider and at least one needs to have a rigidbody - generally the object(s) which are moving. The message will execute within scripts attached to one of the objects, or their parent.

I don't really grasp how you have this all organized, but it seems strange that the panel has a rigidbody. If you are trying to detect an event between the trigger and the button, then one of those objects needs to have a rigidbody...

What object is the VRButton script attached to, anyway?

languid spire
#

the button needs one

queen adder
#

the button has a box collider with is trigger checked.

Button panel has a mesh collider.

The trigger underneath the button has a box collider with is trigger checked.

#

so pannel doesn't need rigidbody?

languid spire
#

the object with the rigidbody will receive the trigger events

queen adder
#

the red button model is the one with the script attached

languid spire
#

then the rigidbody needs to be on the button as well

queen adder
#

it has one

raw token
# queen adder it has one

So in this situation, other is the trigger, which will not have your button tag on it. You can double check by throwing like a

Debug.Log(other.gameObject.name);

in at the top of your OnTriggerEnter() method, outside of the if statement

languid spire
#

you are checking a tag but your cube is untagged

#

this is why you dont crop screenshots

queen adder
#

I'm glad it was that simple lol

#

works now!

#

hazzah :D

#

now to figure out how to add a pistol

#

fuck.

trail harbor
#

What is the correct way to change mesh runtime?
I'm switching skins and the animator doesnt automatically rebind, have to toggle the component in inspector, and the head is weird, how are you guys doing it?

#

I could ofcourse keep him in some anim that doesnt move the head at all, but the animation is still frozen when changing body, any tips?

sand heath
#

you're changing just the head model?

#

oh wait are you instantiating a new body to replace the old one?

ripe shard
trail harbor
#

Yes, instantiating a new

#

Thanks for the answers I will try something else, maybe keeping the animator on the instantiated model instead of root

ripe shard
#

why do you want to keep the animator?

#

you can just force a new one into the same state

trail harbor
#

My animator is at the root, i am instantiating under it, seems the animator does not automatically reconfigure or what ever it is called

#

So maybe moving the animator to the skin instead will do the trick

ivory breach
#

My enemy plane turns upside down whenever it tries to face left, and I have no clue why

crisp prism
#
            if (ScoreDisplay != null)
            {
                ScoreDisplay.text = PlayerScore.ToString(); // Display the player score
            }
            else
            {
                Debug.LogError("Score GameObject does not have a Text component.");
            }
#

why cant I pull the text component

polar acorn
polar acorn
# crisp prism

That's a TextMeshProUGUI. You could also use the shared parent class TMP_Text

crisp prism
#

thank you

ivory breach
worthy merlin
#

I was hoping to get a bit of explanation to this. I am trying to generate an array of TileBase variables that matches the amount needed for a BoundsInt variable. However whenever I run my Tilemap.SetTilesBlock Function it sends the attached error.

The confusing part is that if the total amount of tiles in the array does not match exactly how many tiles are required, the function errors out. But if it knows that the array doesn't match whether it is too high or low... Shouldn't it have a function that would allow me to directly collect that information from the BoundsInt or at least some other similar function. Without doing some math on the min and max values? Just feels strange that it is going to lecture me as if it knows how many are required instead of just giving me a function to match how many are required...

worthy merlin
mint remnant
#

Not sure how you'd get much faster than that calc

worthy merlin
#

I just mean that I feel like it should've had at least some form of code such as wallBounds.size.volume that would've calculated it for us already since its going to be repeated depending on the project. Not complaining, I was just confused if I am missing something or if this is how its done.

teal viper
teal viper
mint remnant
#

drag it into project as a prefab

#

once it's a prefab, now drag one from assets into scene, it will be a game object on its own

#

you can't just abandon your children!

eternal needle
#

Why would you want this? Any specific reason because you'd likely have to do this in whatever modeling tool it was made in (assuming by the names this is some model)

#

Also not a coding question

#

Well not sure why you'd write that (after my message above) but 🤷‍♂️ that's a block

mint remnant
#

another happy customer

north oar
#

i want a prefab to keep acclereating its movement but im not sure how i would apply a move speed variable to each prefab that change independently of eachother

eternal needle
teal viper
#

Also, share the !code correctly next time:

eternal falconBOT
royal linden
#

hello im not sure why its underlined

wintry quarry
#

it will tell you why

mint remnant
#

you're trying to return from a yield and you can't there, can only return void

wintry quarry
#

also this is guaranteed to freeze your Unity editor @royal linden

ivory breach
royal linden
toxic frigate
#

yield return new WaitForSeconds can only be used in a coroutine

wintry quarry
#

To make it a coroutine void needs to be changed to IEnumerator

#

but also - it makes no sense right now since there's nothing in the while loop

#

that will ever change AbleToThrow

royal linden
#

sorry im new so i have to use what i know

#

also what is void

mint remnant
#

you should really go back a few steps, first learn some C#

wintry quarry
#

you have no idea what that means

wintry quarry
royal linden
#

i searched up how to wait a second

wintry quarry
#

go back

#

and read it again

royal linden
cloud burrow
#

Hello guys. Im a beginner in unity and c# and using brakeys how to make an fps tutorial on youtube. Ive tried to make my player move but this shows up when i press any of the WASD keys.
my player motor script is


[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour
{

   private Vector3 velocity = Vector3.zero;
   private Rigidbody rb;
   private Transform Transform;

   void start()
   {
    rb = GetComponent<Rigidbody>();
     Transform = GetComponent<Transform>();
   }

   public void Move (Vector3 _velocity)
   {
        velocity = _velocity;
   }

//Run every physics iteration
   void FixedUpdate()
   {
    PerformMovement();
   }

   void PerformMovement()
   {
    if (velocity != Vector3.zero)
    {
        rb.MovePosition(Transform.position + velocity * Time.fixedDeltaTime);
    }
   }
}

and my player controller script is


[RequireComponent(typeof(PlayerMotor))]
public class Player_Controller : MonoBehaviour
{
    
    [SerializeField]
    private float speed = 5f;

    private PlayerMotor motor;

    void Start()
    {
        motor = GetComponent<PlayerMotor>();
    }

    void Update()
    {

        //Calculate movement velocity as a 3d vector
        float _xMov = Input.GetAxisRaw("Horizontal");
        float _zMov = Input.GetAxisRaw("Vertical");

        Vector3 _movHorizontal = transform.right * _xMov; 
        Vector3 _movVertical = transform.forward * _zMov; 

        //Final movement vector
        Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;

        //Apply Movement
        motor.Move(_velocity);
    }

}```
wintry quarry
wintry quarry
#

It's like you found "pull the trigger to shoot the gun" without the part where you load the gun and rack the slide first

royal linden
#

does anyone know why the script is not running at all

ivory bobcat
mint remnant
#

because you are now using IEnumerator Start()

royal linden
mint remnant
#

you're fishing with some faulty worms, you need to back up and learn some basic C# first, like what does it mean to return void from a method

royal linden
#

not sure

#

it says i cant use void when i try use waitforseconds

mint remnant
#

and that's true

#

it's also true that Unity requires a void Start() mthod to start, so you can't use both

ivory bobcat
royal linden
#

idk i started 1 day agonotlikethis

mint remnant
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ivory bobcat
wintry quarry
wintry quarry
royal linden
#

to my bean guy

worthy veldt
polar acorn
royal linden
queen adder
worthy veldt
#

you cant restart life notlikethis

royal linden
#

yepp

royal linden
ivory bobcat
royal linden
ivory bobcat
royal linden
#

ok

cloud burrow
ivory bobcat
#

start() should be Start() btw

mint remnant
#

good eye, that probably caused rb to not get assigned too

cloud burrow
#

line 31 would be this

#

rb.MovePosition(Transform.position + velocity * Time.fixedDeltaTime);

cloud burrow
cloud burrow
#

i feel so stupid rn

raw token
#

That's the feeling of learning 🌈

mint remnant
#

if your ide is configured right it should give you the code to drop in there as soon as you start typing Sta...

cloud burrow
umbral bough
#

Hi, I've been using this for ages in my game managers etc. and I just ran into an issue where the first one somehow returns null and the second one works fine, could somebody please explain what's actually going on?

public static Camera Camera => Instance._camera ?? (Instance._camera = Camera.main);
public static Camera Camera => Instance._camera == null ? Instance._camera = Camera.main : Instance._camera;
umbral bough
raw token
umbral bough
sick storm
#

Hi i am trying to make my walljump work with my shooting mechanic and my problem is when i jump from one wall to another the space key input makes it so when i jump from a wall to another wall it thinks i have jumped twice switching my direction the wrong way https://hastebin.com/share/ucitovapey.rust

#

i haved tried input.getkeydown as well and the whole thing i pasted does not work

umbral bough
mint remnant
sick storm
#

elsewhere

#

i can paste the full code if you want but im pretty sure what i sent is the issue

ivory breach
#

Update: Every minute I spend trying to make the big plane rotate in a way akin to Luftrausers' planes, I grow more and more frustrated trying to solve the "plane is upside down when they're looking at one side" issue

private void RotatePlane()
    {
        var heading = _target.GetComponent<Rigidbody>().position - transform.position;

        var rotation = Quaternion.LookRotation(heading, new Vector3(0, 0, -1));

        _rb.MoveRotation(Quaternion.RotateTowards(transform.localRotation, rotation, _rotateSpeed * Time.deltaTime));

        _model.transform.localRotation = Quaternion.Euler(0, 0, transform.localEulerAngles.x + 90.0f);
    }
#

If somebody can help me find an answer to end this struggle, I will be eternally grateful

copper orbit
#

if the project is in urp3d but the gameobjects are spritebillboards, would it be best to use collider3d or 2d? I would think its 3d but I cannot get the OnCollisionEnter to work

#

Everything has collider/rigidbody

mint remnant
waxen adder
#

Quick Question: Setting up a first person controller and want to implement source like movement (like everyone else lol). Wondering if a Rigidbody or a Character Controller would be better for this?

queen adder
#

Sorry i suck at rotation/Quaternions stuff, Trying to look up a fix right now but can't promise anything D:

ivory breach
teal viper
#

Why is the second parameter a constant with that particular value?

ivory breach
#

Without the "_model.transform.localRotation" line, it will be facing the player this way without rolling the plane in the process

#

Also, I'm referencing the main game object and the model's game object separately to make it roll when it turns right now

#

The main object turns while the model rolls

teal viper
#

*you want it's up direction to always face the camera?

ivory breach
#

At least for the main object's rotation

teal viper
#

Okay, then that line is fine.

#

Or at least the second parameter.

#

Try using the rotation directly in the rb MoveRotation and don't set the model rotation.

ivory breach
#

@teal viper This what I got after I disabled the model rotation and changed the MoveRotation to this

_rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, rotation, _rotateSpeed * Time.deltaTime));
#

The plane apparently turns just fine

teal viper
ivory breach
runic urchin
#

hey, im converting my project to URP and the material upgrades are wigging out saying this. anyone got any ideas?

ivory breach
#

But the code I used to turn the player is very different, so I can't recreate it to achieve the same effect for the other plane

royal linden
#

does anyone know how i can add a wait time

#

in a while loop

mint remnant
royal linden
teal viper
ivory breach
#

@teal viper I want to achieve a similar thing for the enemy plane

teal viper
#

It kinda looks like you had before.
But you said that "you want it's up direction to always face the camera".
So which one is it? Can you be more consistent in your replies?

frail slate
#

Is it possible to have a material with a canvas shader in URP to have material instancing? I have a UI shader material for the user's pfp, and I want to change the texture individually for each item on the board. But when I change one, it changes the other one as well. Is there anyway around this, or a fix to this?

ivory breach
#

But when it looks to the left, the plane starts to roll upside down

teal viper
#

In neither of these screenshots the up direction faces the camera

ivory breach
#

Actually, it still does

teal viper
#

I don't know what you have selected, but the model doesn't

#

It's clearly facing downwards

ivory breach
#

This is the main object's transform

#

And this is the model's

teal viper
teal viper
ivory breach
#

I sincerely apologize if my replies aren't very understandable, I'm so tired of figuring out a solution to this problem I can't think of how to respond clearly

teal viper
#

Write it down on paper. How do you want the plane to behave in different situations. Draw some diagrams if needed. We can't help you if we don't know what you're trying to achieve. And it kinda feels like you don't understand that entirely either.

ivory breach
frail slate
ivory breach
#

Implementing a Luftrausers-like plane rotation for enemies in Unity is going to be harder than I thought

teal viper
royal linden
#

hello does anyone know why over time my frames get worse and worse

mint remnant
#

you're never destroying the objects you create, nor can you

summer stump
silk beacon
#

yah the prefab could have its own timer

royal linden
silk beacon
#

polling objects might be more performant

#

@royal linden if you are not destroying the objects? where are they going. they take up memory. throw a million and you could crash

summer stump
silk beacon
#

yah profiler is what i was going to say first. see where memory is eating up and why framerate is getting slow.

royal linden
mint remnant
#

considering an hour or 2 ago, you didn't know what void meant, I doubt you're ever destroying them, are they piling up in the heairarchy?

summer stump
#

You can start multiple coroutines at the same time, so that is my guess

royal linden
ivory breach
#

@teal viper Not sure if you can understand this, but this is how I expect the enemy plane to rotate when it turns

summer stump
#

Then it should wait for throwCooldown seconds

summer stump
eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

summer stump
#

Show code properly

eternal falconBOT
ivory breach
#

It would be a better idea to use a site like gdl.space for this

summer stump
#
  1. backticks not apostraphes. And three, not four
  2. do not format code here, use a paste site
#

Delete that and do a site

teal viper
royal linden
frail slate
#

How do you assign a property to a material for only one instance for UIs? Applying images seems to apply for every other instance.

summer stump
ivory breach
#

I'll just paste the code snippet here for convenience

private void RotatePlane()
    {
        var heading = _target.GetComponent<Rigidbody>().position - transform.position;

        var rotation = Quaternion.LookRotation(heading, new Vector3(0, 0, -1));

        _rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, rotation, _rotateSpeed * Time.deltaTime));

        _model.transform.localRotation = Quaternion.Euler(0, 0, transform.localEulerAngles.x + 90.0f);
    }
summer stump
royal linden
teal viper
summer stump
ivory breach
royal linden
summer stump
royal linden
#

one

summer stump
#

Then it should definitely only create one per second. Do you perhaps have more than one of these classes attached to the object?

There is nothing in the code that could cause it to happen more often than that

royal linden
#

i cant see the object spawning either

summer stump
#

Wait, so the issue is that it is not spawning? Or spawing invisibly? Or what? I thought you meant it was happening too frequently

royal linden
#

for some reason

royal linden
#

ok nvm i fixed it 🦾

silk beacon
#

was it too small?

ivory breach
#

I'm still a bit stumped so please bear with me

frail slate
ivory breach
#

Nice

#

Now to figure out how to apply this new direction for the model's up transform

ivory breach
opal zealot
#

I'm following a tutorial that allows me to detect clicks on a Collider Component for 2D, but I plan to use it for 3D objects. Do I need to change anything from this script?: https://hastebin.com/share/ganecuneya.csharp
Or can I keep it as it is without any needed conversions for 3D projects in Unity?

ivory breach
#

I tried applying the model's transform after the model rotation line like this and now it's stuck looking up

_model.transform.localRotation = Quaternion.Euler(0, 0, transform.localEulerAngles.x + 90);
_model.transform.up = combinedDir;
#

@teal viper What am I missing here?

teal viper
ivory breach
#

Btw, the enemy plane starts in this orientation

teal viper
ivory breach
#

I can fix it by rotating the main object in the x-axis by 90 degrees, but it messes up its rotation value of the other two axes when I try to rotate the plane after that

#

@teal viper Idk why that happens, but should I proceed anyway?

teal viper
ivory breach
#

Sure thing! I'll send my project in your dms if you are interested

#

MAN this problem's giving me quite a headache

teal viper
tiny plaza
#

hey can someone explain to me what it means when a function returns something

ivory breach
#

@teal viper I've sent my project in your dms

toxic yacht
tiny plaza
#

and what about parameters?

toxic yacht
#

Parameters and arguments are synonymous

cosmic dagger
ivory bobcat
#
int argument = 5;
Method(argument);``````cs
private void Method(int parameter) {}```
upper tide
#

When you try to use a function like OnCollisionEnter2D, does the function parameter NAME have to be exactly the same? As in, if I write Collision2D collider instead, would there be any consequences? Also I'm not quite sure how we're using this, since I don't see an override anywhere so I assume this isn't an inheritance thing, or is it interface based?

mint remnant
#

would be hte same

#

only the type matters

drowsy flare
upper tide
drowsy flare
#

Okay so I have a 2D game where characters walk around from side perspective, Monkey Island style.
I want to have rigidbodies so the characters have to walk around each other. However they should be able to pass each other in perspective, and partially cover each other. This leads me to a possible solution where I could put the collider 2D around the characters feet, and they should be able to pass each other close, but not stand on the same spot, in a nice fashion.

However, I want them to also be able to shoot each other. So I want a collider over the entire character as well. How would I go about this?

static bay
#

Have a collider act as the collision for the world.

#

And create a different collider (on some Hurtbox layer) to act as the collider for attacks.

drowsy flare
drowsy flare
#

Seems to work

drowsy flare
opal zealot
#

The ones are youtube are mostly old(So I'm unsure if they'll work on newer ver of Unity).

molten dock
#

Make a raycast to the mouse position

drowsy flare
opal zealot
# molten dock Make a raycast to the mouse position

Following a tutorial: https://www.youtube.com/watch?v=aaYfoe9i5lY
Though this time synced to Unity's Input System. However, I'm unsure how to tie it in Via the 'Input' type: https://hastebin.com/share/jalukasuso.csharp

In this video we will go over how to select an object using the mouse and on how to use the unity raycast to get a gameobject, how to use maskLayer to make sure we are not selecting other objects, drawing the raycast in and editor using Debug.Drawray and more!

All the code in the tutorial:
https://www.nerdhead.dev/post/selection-with-raycast-u...

▶ Play video
arctic ibex
#

Guys, urgent help needed. The submission date it in half an hour. Time.timescale is effecting LITERALLY nothing

#

lemme send th ecode rq

#

This is the code that runs to set Time.timescale. All of the degub happen.

#

The time.timescale debug returns 0

#

all of the rigid bodies move as normal, so do the animations.

#

even the animations on normal time

#

okay, all good. Turns out another script was setting time scale every update

upper tide
#

At what point is it considered overusing scriptableObjects? I tend to use them when theres a lot of parameter data needed for setup, like say movement values damage numbers

#

Also sprite changes, i store them in an array of sprites in SO instead of in the mono behaviour directly

#

It feels more fluid to me for some reason

fickle plume
eternal needle
fickle plume
#

If you just want to serialize several fields on prefab (as a simple object you can pass around) you would be better with simple serialized class object there.

fickle plume
# upper tide At what point is it considered overusing scriptableObjects? I tend to use them w...

Should check this talk really. https://youtu.be/raQ3iHhE_Kk

Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns. In this talk, Schell Games shares specific examples of how they have used the Scriptable Object for everything from a hierarchical state machine...

▶ Play video
upper tide
tender stratus
#

hey guys, im designing my first game and was wondering how games make character creation

#

like is that an achievable goal or is it quite hard

#

to allow the yser to create a custom character

languid spire
naive locust
#

is it possible to make functions accessible from other scripts?

languid spire
naive locust
#

so

public void functionname ()
{
// code
}

?

languid spire
#

yep

naive locust
#

is calling the function the exact same?

languid spire
#

you will need a reference to the instance of the class but, yes

naive locust
#

oh ok thx

#

yeah i got it working

lost basin
#

Ok wait let me rephrase, how do I add a mesh collider to a randomly generated mesh map, generated from a noise map, that changes every time I generate a new map. I tried just putting a mesh collider onto it, but It wouldn't update with the new map I generated. And I tried the previously mentioned method by PreatorBlue, but my mesh gameObject can't be assigned to the script.

rough hill
#

Why does my ShortcutSlot always starts with an assigned item? On Awake() I set the assigned item to null but that didn't do anything.

tender stratus
languid spire
tender stratus
#

Anyone know why it doesnt work?

#

I tried recalling what i learned yesterday

#

Without youtube and i Dont know whats wrong

languid spire
tender stratus
#

What is that

#

The code runs

languid spire
#

it is the very first thing you should have learned when starting to program for Unity

tender stratus
#

Okay

#

Care to explain?

languid spire
#

Debug.Log allows you to output to the console exactly what your code is doing so you KNOW rather than ASSUME

tender stratus
#

THanks

#

It says my horizontal input isnt setup on unity

#

Weird it worked yesterday

naive locust
#

So I have a bullet that collides with an enemy, how do I make it so the enemy doesn't fly away when it collides with the bullet?
This is in 2D btw

quick fractal
#

Can I have more than one yield return new WaitForSeconds(); in a coroutine? Each time I've tried it I just got an undescriptive error about the Coroutines class

keen dew
#

Yes. You just did something wrong.