#💻┃code-beginner

1 messages · Page 81 of 1

modest barn
#

This is Dropdown.cs now:

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

public class Dropdown : MonoBehaviour
{
    [SerializeField] TMP_Dropdown dropDownObject;
    TMP_Text dropDownValue;
    
    void OnValueChanged()
    {
        dropDownValue = dropDownObject.captionText;
    }
}

And this is the screenshot of the Inspector window when the TMP_Dropdown object is selected.

#

AHHHHH

#

PUBLIC

polar acorn
modest barn
#

Is that it?

rich adder
#

that too

polar acorn
#

and what's the point of this object, you're just storing one string in a different string

modest barn
rich adder
#

also this returns you an int

modest barn
rich adder
#

probably wanna do something with the index of item

modest barn
rich adder
#

your method has no parmaters for the returned value

polar acorn
rich adder
#

if you made it take int then it becomes a dynamic method

modest barn
rich adder
#

yup

modest barn
modest barn
rich adder
#

think of the script on a gameObject as the actual Instance of the script

modest barn
rich adder
#

yeah if gameobject is enabled

modest barn
#

Awesome

rich adder
#

Awake is sort of works like the constructor

modest barn
rich adder
#

did you save any script changes in playmode?

#

cause it usually spams that

modest barn
#

Never mind

#

Yep that's exactly what I did

#

Thanks all! Got it working. What would I do without this server 😆

vital spade
#

Hey there, I've created a heart system through a tutorial and am running into a weird object reference not set to an instance of an object issue even though all references are set correctly, I'll turn this into a thread and post some screenshots and code maybe someone can see whatever it is I'm missing.

amber spruce
#

not sure if i ask this here or in networking but i have my game multiplayer now but im not sure how to change the scene for everyone

rich adder
#

all multiplayer questions go there

amber spruce
#

ah ok thanks

red wind
queen adder
#

Displaying items from a list keeps showing the "item was out of range" error
Hello. I am trying to display a specific item from a list but it keeps saying this error. Heres my code:

#

can i get some help?

polar acorn
abstract finch
#

How would you create this arc using animation curve? Would you apply a force an add it to its current position or would you get the target position then lerp it to the destination? I simply want it to curve in a direction then go downwards until it reaches the ground

queen adder
polar acorn
#

Log the size of answers and the value of arrayOrder

polar acorn
# queen adder

This shows me that there exists at least one answers list with four things in it

queen adder
#

and the log says that also

polar acorn
#

This does not show that you are checking this list

#

Log the length of the answers and the value of arrayOrder the line before the error occurs and show me your console

polar acorn
queen adder
#

arrayOrder = answers.Count()

polar acorn
#

Is this log in the function that has the error

#

or is this the same one in Start that doesn't help

queen adder
#

the same

#

imma log it in the function

#

one sec

polar acorn
#

Log arrayOrder and the length of the list

#

Two different numbers. Give them some sort of identifier so you can see which is which

meager gust
queen adder
#

heres arrayOrder for the first and second answer

#

@polar acorn

polar acorn
polar acorn
queen adder
polar acorn
#

The first one is logging the length of questionItem. The second is question

#

For that matter, why are your variables of type GameObject when all you do is get components from them, those should be of type Question to begin with

queen adder
#

okay

north kiln
#

Also, if answers is an array, use .Length, if it's a list, use .Count, you should only use .Count() if the others are not present

amber spruce
#

any ideas why my variables and stuff are public but dont show up in the inspector

#
    public NetworkManager NetworkManager;
polar acorn
amber spruce
#

nope

polar acorn
#

Is NetworkManager a serializable type?

amber spruce
#

i believe so

boreal oxide
#

Is it because the names are the exact same?

amber spruce
#

i have this in there aswell

public float heartbeatTimer;
#

thats whats confusing i have a lot of variables in there that are public

rich adder
#

why do you need a field for network manager?

amber spruce
#

so it can access stuff from it

rich adder
#

it already has a singleton to you can access no ?

amber spruce
#

idk

#

idk what i did but now i see the variabels

rich adder
#

is this a Unity Component ?

amber spruce
#

the network manager is from the netcode for game objects

rich adder
#

you juse use the .Singleton

#

you don't have to make a field for it

amber spruce
#

ok thanks

summer stump
solemn fractal
unreal imp
#

Guys, here again I am trying to make the player able to load, drop and throw objects (objects up to a certain mass or weight) but it doesn't work for me, here is the code https://gdl.space/xupobugagu.cs

#

don't laugh at this, it's just beginning 🙂

quick ruin
#

this should add the left to the right and its not

wintry quarry
#

the LEFT side of = will change

#

the right side is just an expression to assign to the left.

quick ruin
#

ok ty

wintry quarry
#

x is the thing that changes

rich adder
quartz anvil
#

Anyone know how to pass on object already in the scene to a field in a prefab that isn't already in the scene? im trying to drag and drop a UI element onto my prefab that should spawn when a key is pressed and a menu should pop up. just can't seem to get the reference to that menu to make it pop up.

quartz anvil
#

@rich adder Ty ❤️

fossil drum
#
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        direction = new Vector3(moveHorizontal, 0.0f, moveVertical);
        direction = transform.TransformDirection(direction);
        Debug.Log($"H:{moveHorizontal} V:{moveVertical} Dir:{direction}");

Add this debug.log to your code and show what it logs in your console

tiny vault
#

oh wait

#

found it

fossil drum
#

You have written this right? Or is this chatGPT code I'm fixing now?

tiny vault
#

this is what it says

fossil drum
#

So you have a little bit of input, do you perhaps have an Xbox controller or steering wheel attached?

tiny vault
#

no i dont

#

by the way if i turn on the "is kinematic" option on rigidbody component it doesnt do that

fossil drum
#

Of course, because Kinematic removes all physics, and you move with physics.

tiny vault
#

oh okay then it has to be off

fossil drum
#

Yeah for sure.

#

Anyhow, you have an analog input signal somewhere coming in from some device.

tiny vault
#

is there any way to solve it

#

when the character hits a wall it bounces and keeps moving by itself

fossil drum
#

That seems like a completely different issue, anyhow, the fact that you are moving is because you have input. You can just force the values to 0 and see if that's the cause. Then figure out where it's coming from.

tiny vault
#

i set them to 0 but it stills does the same thing

fossil drum
tiny vault
#

do i like need to do anything on input manager

#

u think?

amber spruce
#

how do i get the active scene

amber spruce
#

thanks

pearl flower
#

I have a problem that if I press on different elements of UI, for example, button and also use touch then in some cases touch field is interrupted by other element of UI. Like pointerId it starts associates with different UI element, but we still use it.

#

How can I fix it, explanation of problem is above.

unreal imp
languid spire
eternal falconBOT
rich adder
unreal imp
# rich adder what have you tried to debug this ?

I made 4: one to detect when the player has an object in front of him and that has a mass of 15kg or less (to prevent him from lifting objects heavier than him), another debug to detect when he is carrying an object, another to when he releases it and the last one is to throw it

rich adder
#

yes logs are a start but not all of debugging

#

also your logs are kinda useless atm

flat eagle
rich adder
#

you need to debug specific information / values @unreal imp

#

that makes it more useufl

unreal imp
#

ahhh like renaming the debug

rich adder
rich adder
#

it would make more sense to make it Debug.Log($"Raycast has hit {hit.collider.name}");

#

for example or
Debug.Log( $"Do we have g? {g.transform.parent} and are carrying ? {isCarryingOBJ}")

flat eagle
#

why the script get Dropdown, still have Monobehaviour

flat eagle
tiny vault
flat eagle
#

are very important

rich adder
#

player hit itself, and carries itself

#

script is working, just not the way you intended

unreal imp
#

;/

rich adder
#

use layermask and exclude player from raycast

unreal imp
#

oh thanks

obtuse oar
#
            velocity = curr.velocity;
            curr.MovePosition(Vector2.SmoothDamp(curr.position, mousePoint, ref velocity, 0.025f));

why is the argument curr.velocity invalid requiring the use of velocity, they're both vector2s. I'm just not understanding the error and would like to remove the seemingly unnecessary line

fathom timber
#

you can't ref a property, like the error says

obtuse oar
#

yeah i'm confused on what that means specifically

fathom timber
#

you can just put the property into another variable and ref that, then set the property

#

so like
var velocity = curr.velocity
Function (ref velocity)
curr.velocity = velocity

obtuse oar
#

yeah that's what i'm doing already in the code posted

#

i was just curious as to the reasoning why that is needed

rich adder
fathom timber
#

oh, that's how properties work in C#, you should look up properties for more information on that

obtuse oar
#

hm okay

#

so the line is required then i suppose

fathom timber
#

yeah

obtuse oar
#

tsk tsk, stupid extra loc

swift crag
#

Many things that look like fields on Unity objects are actually properties

fathom timber
short hazel
#

It's more because a property is a pair of functions that access a value, and not the value itself

#

Can't ref a method, so this error is reported

fathom timber
#

^ yeah this

obtuse oar
#

is there a different method that returns the velocity in a form that can be referenced? pointless questions at this point but i'm just curious now

#

or is it that the ref means it needs a value specifically and not the return of a method

median elk
#

Im getting two Null reference exception on GUI Box

#

here is the part of the problem , line 146 and 259

short hazel
median elk
fathom timber
#

is GUI.ski.FindStyle null? Can you isolate that?

short hazel
#

The non-monospace font is really cursed

dusk hornet
#

i need help if i chose proccess events in dynamic update when i press e in game it dosent work alawys and the camera works fine when i choose on process events in fixed update the input works fine and the camera moves fast

fathom timber
dusk hornet
#

this is the code

short hazel
slender nymph
# dusk hornet

wasPressedThisFrame will only be true the first frame the key is pressed. and since OnTriggerStay only happens on physics update frames it may not have been pressed that frame, it likely was pressed on a frame between FixedUpdates.

#

a better way of handling interactions would instead be to use physics queries like raycasts instead of relying on OnTriggerStay to determine if the player is in range of an interactable object

dusk hornet
#

i m not really good at coding idk if i can do the raycasts one

slender nymph
#

better get to learning

rich adder
#

if ur gonna poll inputs then make a bool in update

dusk hornet
#

or that dosent work like that

slender nymph
#
  1. use cinemachine
  2. you'd have to show the relevant code for that if you want help with it
dusk hornet
#

code of what

slender nymph
#

the camera . . .

pearl flower
slender nymph
rich adder
# dusk hornet
bool eKeyPressed => Keyboard.current.eKey.wasPressedThisFrame;``` 😏
#

psudo :

bool isInTrigger ;
OnTriggerEnter ()   isInTrigger = true;
OnTriggerExit()    isInTrigger = false;
Update () if(isInTrigger && eKeypressed )// Do Stuff```
rich adder
dusk hornet
rich adder
# dusk hornet

anyway, look at the bool trigger example. You can still use Keyboard.current.eKey.wasPressedThisFrame; is just long to write for no good reason..

pearl flower
#

https://paste.ofcode.org/XmyEeEUDKa3uBS3pPubm2w
I have a problem that if I press on different elements of UI, for example, button and also use touch then in some cases touch field is interrupted by other element of UI. Like pointerId it starts associates with different UI element, but we still use it. And camera starts sliding.

quick ruin
#

How do I set Time.time.ToString() to use 1.00 minute second format

fathom timber
#

.ToString("D2") (if I recall correctly)

short hazel
#

(you'll have to divide the value by 60 to convert to minutes)

#

Ah that'll be F2 for the format string, D is for integers (it pads the numbers with zeroes: eg. D4 => 0042)

weary moss
#

this code is supposed to detect the screen's dimensions and readjust the object it's attached to the size of the screen. but, let's say the base size of the object is 800x480, it doesn't matter the size of the screen, the x scale will always be slightly off.

void Start()
{
    transform.position = new Vector3(camera.transform.position.x, camera.transform.position.y, transform.position.z);
    Vector3 InfEsq = camera.ViewportToScreenPoint(Vector3.zero);
    Vector3 SupDir = camera.ViewportToScreenPoint(new Vector3(camera.rect.width, camera.rect.height));
    Vector3 TamanhoTela = SupDir - InfEsq;
    float EscalaTela = TamanhoTela.x / TamanhoTela.y;
    float EscalaLocal = transform.localScale.x / transform.localScale.y;

    if (EscalaTela > EscalaLocal)
    {
        float altura = TamanhoTela.y;
        transform.localScale = new Vector3(altura * EscalaLocal, altura);
    }
    else
    {
        float largura = TamanhoTela.x;
        transform.localScale = new Vector3(largura, largura / EscalaLocal);
    }
}

What am i doing wrong

median elk
fathom timber
fathom timber
#

is it a custom GUISkin asset?

median elk
#

i get these two null refs when importing this

median elk
median elk
fathom timber
#

Well unfortunately I can only read English so I can't understand this. But to fix that error I think you can just remove that FindStyle line and it will probably be fine? Might look a bit weird.

#

but it will at least compile

fathom timber
#

Nah just delete this part, it's an optional parameter

slender nymph
#

make sure that your !IDE is configured so that it will highlight basic syntax errors like that

eternal falconBOT
median elk
#

is it something wrong with line 127 and 237 too? on the null reference stack , something is also mentioned about these 2 lines

rare basin
#

It's call trace

swift crag
#

when you get an exception, a stack trace is printed. each line in the stack trace is a method

#

the top of the stack trace is where the error occurred. the line below it is its caller

#

(this goes all the way down the stack)

median elk
#

I see, but it's odd how these 2 nulls keep coming even after I have commented the whole line

atomic idol
#

hey guys im trying to make a game with sprinting but the friction of the floor makes me have to use high numbers exceeding the max speed i want for movement making sprinting useless, and also impossible to walk slowly i want it so

1:i can walk normally and the speed will be below the max speed of 50 (hopefully around 3

2: i want sprinting to make you reach 10 speed

3: the friction of the ground to not be slippery but still allow movement

(i got all of the code except the sprinting from the youtuber dani all i added was sprinting and a few adjustments)
https://paste.ofcode.org/39tXGg388C6Xs6Ag8YTRGjv (code here)

eternal falconBOT
atomic idol
#

oh sorry

queen adder
#

i want to make a game but i have no clue where to start

zealous atlas
amber spruce
#

how do i reference a object that gets spawned in so its a prefab and gets instantiated in but i wanna reference it in another script

zealous atlas
queen adder
#

dident he stop making videos?

zealous atlas
atomic idol
queen adder
#

ok thank you

#

i added you batty

zealous atlas
swift crag
#

explain the gameplay, not how you're trying to implement it

queen adder
#

is it a good idea to follow a video on how to make flappy bird to learn?

amber spruce
#

so basically i have enemies that stay even after a new scene is loaded and when that new scene loads i want smth to happen to them

teal viper
queen adder
#

bro hello world in c# is So much harder then python lol

swift crag
eternal needle
swift crag
#

You should keep a list of all of the enemies somewhere.

#

You could put this on the component that spawns them, for example

eternal needle
queen adder
#

im not struggling with it i was just saying its so much harder for new people lol

atomic idol
queen adder
#

yea but im not having problems with it i understand coding lol

amber spruce
zealous atlas
pearl flower
amber spruce
eternal needle
# queen adder yea but im not having problems with it i understand coding lol

then you should have a good understanding on how to answer your first question. You dont need to overstate your skills, you are asking in the beginner channel for a reason. These arent insults by saying you are a beginner. Your initial messages and claiming you understand coding are very contradictory.
My suggestion still stands, do basic c# then unity. Yes you can follow a video (flappy bird or not) to learn, whether its a good idea or not depends how much you truly understand coding. For ex: if you have a degree in computer science, then I wouldnt suggest following such a beginner tutorial

pearl flower
#

For example.

#

Does enemy have scripts?

amber spruce
#

yeah

pearl flower
#

So, specify your script.

#

That's it.

timber tide
#

Searching the scene is always bad, but it's not likely yall making projects with 10000+ trees in it

#

but still, large linear search

#

yikes

pearl flower
#

Well, it's only in start, so it's not bad.

amber spruce
#

well my game is a 2d game so not that much stuff

eternal needle
pearl flower
eternal needle
austere monolith
#

i was making a pickup and drop system but when i put the game on, the gun just goes in a random place, locks in, and rotates with the camera, i drop it and pick it back up, then it starts raising while im spinning around in the camera is there something i can show for help?

ruby ember
#

hi everyone so i want to add 2 things

  1. Music Toggle turn on music and turn off music

  2. Quality DropDown

and i need help or send code

the quality one it only has 3
Low Medium and High

eternal needle
amber spruce
ruby ember
eternal needle
#

Setting the volume to 0 should be easiest then

amber spruce
eternal needle
# amber spruce

I dont know how this is related to the enemy stuff you posted above. This very cropped screenshot also really isnt gonna help me help you. All i can is that line never runs, or .Player is null

ruby ember
#

ok code worked but i want it on DropDown

slender nymph
#

you're not meant to just copy/paste the example code. it shows you an example of how to use it

#

take that information and add the options to your dropdown menu instead of imgui buttons

ruby ember
#

i kinda don't know coding

slender nymph
#

there are beginner courses pinned in this channel

eternal needle
#

honestly didnt even look at the code that was on the doc, i was just sending the method name 😅

amber spruce
#

how do i disable a rigidbody

slender nymph
#

you don't. you can remove the component or make it kinematic though

#

or you could just set the gameobject inactive, but that affects more than just the rigidbody of course

amber spruce
#

so how would i just have it not able to move

slender nymph
#

make it kinematic and just don't move it

amber spruce
#

can you do that in code

ruby ember
#

i feel that i did it really bad

summer stump
amber spruce
#

and that will make stuff like gravity not affect it

summer stump
slender nymph
eternal needle
# ruby ember i feel that i did it really bad

the only part of the code you need is QualitySettings.SetQualityLevel. The rest of it is to make a GUI layout which you do not need to do through code. Use your own buttons and give them a listener through code for the quality level

ruby ember
amber spruce
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OnSpawn : MonoBehaviour
{
    public static OnSpawn Instance { get; private set; }
    public Rigidbody2D rb;
    public SpriteRenderer sr;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        sr = GetComponent<SpriteRenderer>();
        rb.isKinematic = true;
        sr.enabled = false;
        DontDestroyOnLoad(gameObject);
    }
}

i dont have that variable anymore why is that still there

#

the player one

static cedar
timber tide
#

compile errors

#

always expect them

static cedar
#

Would rebuilding help?

forest karma
#

I have this error and I'm not sure how to fix it

austere monolith
rich adder
rich adder
austere monolith
#

i did

#

the exact same thing he did

#

still bugs

rich adder
#

then show code and the vid

austere monolith
#

bro its massive

#

for discord i mean

rich adder
#

!code

eternal falconBOT
austere monolith
#

i would need nitro

rich adder
#

use link

#

also don't crosspost

austere monolith
#

huh?

#

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

public class PickUpController : MonoBehaviour
{
public ShootingScript3D gunScript;
public Rigidbody rb;
public BoxCollider coll;
public Transform player, gunContainer, fpsCam;

public float pickUpRange;
public float dropForwardForce, dropUpwardForce;

public bool equipped;
public static bool slotFull;

private void Start()
{
        if (equipped)
{
    // Set the initial position and rotation relative to the camera
    transform.SetParent(gunContainer);
    transform.localPosition = Vector3.zero;
    transform.localRotation = Quaternion.Euler(Vector3.zero);
    transform.localScale = Vector3.one;

    // Make Rigidbody kinematic and BoxCollider a trigger
    rb.isKinematic = true;
    coll.isTrigger = true;

    // Enable script
    gunScript.enabled = true;
#

}
else
{
// If not equipped, ensure the gun is in the correct state
gunScript.enabled = false;
rb.isKinematic = false;
coll.isTrigger = false;
}
}

private void Update()
{
    //Check if player is in range and "E" is pressed
    Vector3 distanceToPlayer = player.position - transform.position;
    if (!equipped && distanceToPlayer.magnitude <= pickUpRange && Input.GetKeyDown(KeyCode.E) && !slotFull) PickUp();

    //Drop if equipped and "Q" is pressed
    if (equipped && Input.GetKeyDown(KeyCode.Q)) Drop();
}

private void PickUp()
{
    equipped = true;
    slotFull = true;

    //Make weapon a child of the camera and move it to default position
    transform.SetParent(gunContainer);
    transform.localPosition = Vector3.zero;
    transform.localRotation = Quaternion.Euler(Vector3.zero);
    transform.localScale = Vector3.one;

    //Make Rigidbody kinematic and BoxCollider a trigger
    rb.isKinematic = true;
    coll.isTrigger = true;

    //Enable script
    gunScript.enabled = true;
}

private void Drop()
{
    equipped = false;
    slotFull = false;

    //Set parent to null
    transform.SetParent(null);

    //Make Rigidbody not kinematic and BoxCollider normal
    rb.isKinematic = false;
    coll.isTrigger = false;

    //Gun carries momentum of player
    rb.velocity = player.GetComponent<Rigidbody>().velocity;

    //AddForce
    rb.AddForce(fpsCam.forward * dropForwardForce, ForceMode.Impulse);
    rb.AddForce(fpsCam.up * dropUpwardForce, ForceMode.Impulse);


    //Disable script
    gunScript.enabled = false;
}

}

teal viper
summer stump
eternal falconBOT
austere monolith
#

how do you even use hastebin?

rich adder
#

you paste code and save, send link. not rocket science

summer stump
austere monolith
austere monolith
rich adder
#

don't see anything in this code that deals with looking

austere monolith
#

then ill show my screen in unity

summer stump
#

Just show the code that deals with looking. This is a pickup and drop class

austere monolith
rich adder
summer stump
#

Maybe it's the ShootingScript3D?

austere monolith
#

thats the gun script

rich adder
#

is prob on the root player or cam

summer stump
#

Can't really know from just what you've shown 🤷‍♂️
All I knos is that it's definitely not the code you showed before

rich adder
#

how you not know your own project lol

#

beyond me.

atomic idol
rich adder
#

if you follow a video don't blindly copy it @austere monolith

#

also send link to that

austere monolith
#

link to what

#

the video?

tulip stag
#

Just a question out of curiosity, not off any project I'm working on rn— can a class initialize a version of itself as a variable?
Let's say, a game where combat is handled in the Fighter script and every player or enemy that can fight has its Fighter component, could you write something like

  {
    [SerializeField] Fighter target;

    private void Update()
    {
        Attack(target);
    }
  ...```
rich adder
austere monolith
#

here

#

FULL PICK UP & DROP SYSTEM || Unity3d Tutorial:
Since I just started my series on how to shoot with projectiles in Unity, I thought it would be cool to share how to make a full pick up and drop system :D

Don't forget to subscribe if you enjoyed the video, and if you have any questions just write a comment, I'll answer as many as I can! :D

Link...

▶ Play video
#

its literally just that one small bug

rich adder
#

you didnt explain your problem properly

austere monolith
#

its a pick up and drop system, i followed the tutorial and put the stuff he wrote, on the script. when i start in the game, i have the equipped on by default. i obviously put together the transforms etc. every time i start the game, the gun starts higher than supposed to and rotates weirdly with my camera, when i drop it then pick it up, its in my hand, but it still rotates with my camera weirdly.

amber spruce
#

how would i reference a variable from one script to another

rich adder
#

or didn't setup something with parenting properly

amber spruce
#

is it possible to get the component if you dont know the object that its attched to

#

because my player is spawned in from a prefab

austere monolith
#

oh shoot, if my player runs on charactercontroller to move, and i need a rigidbody on my player for the pickupcontroller to work, could i still restrain the rotation of xyz, and would it be the same? my camera look is in the main camera so i could still look around

amber spruce
#

thats my player

rich adder
#

You typically make a singleton

#

like it says in link i've sent

austere monolith
#

wait i actually need to know answer my question rq

crisp gate
#

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

amber spruce
dense root
#

How do I reverse my ball's direction? Currently it moves left to right as intended but for fun I want to move it up and down.

private void Launch()
{
    float x = Random.Range(0, 2) == 0 ? -1 : 1;
    float y = Random.Range(0, 2) == 0 ? -1 : 1;
    rb.velocity = new Vector2(speed * x, speed * y);
}
#

Akin to going from PONG to breakout

rich adder
dense root
#

I'm listening :)

rich adder
#

technically reverse of left is right and vice versa no?

dense root
#

Yes

rich adder
#

so you want to go from horizontal to vert?

dense root
#

Yes

#

Here is what is happening upon start:

void Start()
{
    startPosition = transform.position;
    Launch();
}
#

In fact, I'm confused how it gets to launch only left or right in the first place

rich adder
#

the initial direction no?

dense root
#

Yes

rich adder
#

i mean you're pretty much moving in all directions lol

#

rb.velocity = new Vector2(speed * x, speed * y);

dense root
#

lol

#

So how do I go from there to a breakout style movement where it launches towards the player?

rich adder
#

probably less x amounts and more y amounts

#

i bet if already did rb.velocity = new Vector2(speed / 2) * x, speed * y);
or something it be more "breakout"

dense root
#

Nah that just halved the movement speed of the X

#

And interestingly locked the Y movement so it is now just moving side to side

rich adder
#

huh thats why

#

oh wait no

rich adder
ruby ember
#

quality settings is finished but now how can i make the music toggle
i want it when is unchecked the music stops and when is checked the music goes back to the start

dense root
#

@rich adder You're right, I had the Y position frozen

#

Apologies

rich adder
#
[SerializeField] Toggle toggle;
private void OnEnable() => toggle.onValueChanged.AddListener(ToggleChanged);
private void ToggleChanged(bool toggled)
{
    if(toggled)
    {
        //play 
    }
    else
    {
        //stop
    }
}```
ruby ember
rich adder
ruby ember
#

no

#

i said this is another port from another person

rich adder
#

oh

ruby ember
#

this is not mine

#

even i want it like this

rich adder
#

well i told u how to do it already pretty much

rich adder
#

ya

ruby ember
#

btw is this right?

rich adder
#

looks fine

#

why wouldn't they be

ruby ember
#

if im missing another using Unity something

#

but ok

rich adder
#

wdym

#

are you getting an error?

ruby ember
#

no

#

everything good

#

where should i add it?

#

music object (the music)
or in the toggle?

rich adder
#

ideally a script that manages sound

ruby ember
#

is this right (to put it in toggle value)

rich adder
ruby ember
#

the second one is the toggle value

rich adder
#

oh toggle already has event handler

ruby ember
#

so where should i put the script?

rich adder
#

anyway dont use that

#

there is no way to determine if true or false in that event

#

it just fires a method when event is changed

#

putting add listener is the same thing in code

rich adder
#

if thats its job

#

reference the audio player

ruby ember
#

like this?

#

if im not

rich adder
#

u dont need the inspector

#

for event

#

just make a reference to audio source

#
 [SerializeField] AudioSource musicPlayer;
 private void ToggleChanged(bool toggled)
 {
     if(toggled)
     {
         //play 
         musicPlayer.Play();
     }
     else
     {
         //stop
         musicPlayer.Stop();
     }
 }```
ruby ember
#

i need to change the code? or make another one?

rich adder
#

why would you make another one

#

you already have music toggle

ruby ember
#

i mean the script

rich adder
#

its literally that script

#

thats its job

#

toggle music

ruby ember
#

so i need to change the script?

rich adder
#

yes you have to change it to do what u expect it to do

#

code doesn't change itself 😛

ruby ember
#

ok now is changed

ruby ember
rich adder
ruby ember
#

where

rich adder
ruby ember
#

oh

#

ok

#

where where i put the script?

ruby ember
rich adder
#

its not that many lines

#

it should be clear as day whats going on

ruby ember
#

sorry

ruby ember
ruby ember
#

oh

#

let me check

#

wait

#

it didn't work

rich adder
#

what is it?

#

and what did you do

ruby ember
#

im sending video

#

but is loading

rich adder
#

show the code u did

ruby ember
rich adder
#

so how are you calling ToggleChanged ?

ruby ember
rich adder
ruby ember
# rich adder

i need to change the name or the other serializefield or both?

rich adder
summer stump
rich adder
#

right now its private and you got rid of the Listener

#

so how are you calling it

ruby ember
summer stump
summer stump
rich adder
ruby ember
#

it took so long of uploading this

#

sorry

rich adder
#

alr so how do you plan on now receiving the bool if its toggled or not ?

ruby ember
rich adder
#

look careful at the initial messages we spoke about

#

and the code i first sent

#

its still relevant

ruby ember
#

hmm i see

ruby ember
#

on the top

#

sorry for telling that

rich adder
#

when I shown you private it was linked to event still

ruby ember
summer stump
#

What is causing the code to run?

#

Code doesn't just go (unless it's in a Unity method like Start, Update etc, but that takes another explanation that you can read about)

For you own functions, you need to call it somehow

#

It sounds like you were using a Unity Event before?

ruby ember
#

i don't remember

rich adder
ruby ember
#

i need to add that too?

rich adder
#

either that or call the ToggleChanged with the event thru inspector..

summer stump
#

Ah. Yeah, that code is very necessary
OnEnable is one of those Unity methods I mentioned that will be called (somewhat) automatically

#

Yes, or through the inspector

rich adder
ruby ember
#

here's the bool

rich adder
#

ok

#

now you made it private again

ruby ember
#

yes

rich adder
#

ok so you need the bool

#

from the Toggle component

ruby ember
#

this is coding channel

empty obsidian
#

okay sorry where should i ask about that?

ruby ember
empty obsidian
#

okay thx

rich adder
#

dont copy the code

#

just read it a few times

#

so it sink in

ruby ember
#

so i read it some times and i need to add like Toggle.isOn

rich adder
#

no

#

you have to just understand what the hell onValueChanged is for

#

yu should seriously consider going through some unity / c# courses tbh you won't get very far this way

bright nexus
#

Hello I am currently working on a jump behaviour. I have a raycast that checks if the player is grounded. If the player is not grounded I add velocity to the player otherwise it is set to 0. I am constantly moving the player's y position by its current position-the current velocity. This all works as intended except when I start the game the player moves down at an incredible rate for the first few frames. It seems that the velocity is incredibly high when I start the game for some reason. I am doing all my checks in the update function. Does anyone know why the player moves down much faster than it should when I start the game? If you need more information/code please ask.

eternal falconBOT
bright nexus
rich adder
#

wait i dont even see velocity being used anywhere

bright nexus
rich adder
#

ohh you have it twice

bright nexus
bright nexus
bright nexus
# rich adder ohh you have it twice

transform.position = new Vector2(transform.position.x + Xdirection * speed * Time.deltaTime, transform.position.y - VELOCITY * Time.deltaTime); Just pretend it is updated to this

rich adder
#

10-30 = -20 and w.e delta time is

#

now next frame

#

-20 - 30 = -50

#

so its probably going down really fast

bright nexus
rich adder
#

you said you fall faster in the air not grounded or did I misread original Q

#

oh you're saying player is falling at start when they're grounded or they start not grounded ?

bright nexus
rich adder
#

are you certain you're grounded

bright nexus
bright nexus
rich adder
#

oh ok and whats initial vel?

#
f(!isGrounded())
        {
            VELOCITY += gravity * gravitymultipleyer * Time.deltaTime;
          Debug.Log(VELOCITY);
        }```
bright nexus
bright nexus
rich adder
#

yeah you need a max y vel prob

#

unless you want vel to indefinitely increase

bright nexus
bright nexus
rich adder
#

thats not much but depends how much does it get before player IsGrounded

rich adder
#

so its def speeding up

#

by a lot

#

I would also use a rigidbody instead of transforms

bright nexus
# rich adder by a lot

So, if I am understanding this correctly, the velocity speeds up to 26. If I am subtracting the velocity from the players current position every frame, subtracting by 26 will make it go through the floor since the floor doesn't go down to 26?

rich adder
bright nexus
rich adder
#

Time.deltaTime is probably keeping it from completely zooming into oblivion but if you dropped high enough you can pickup enough vel

bright nexus
# rich adder Time.deltaTime is probably keeping it from completely zooming into oblivion but ...

Alright, I have had issues with rigidbodies, and built in physics in the past, so that was the main reason I wanted to try a different approach. I guess I just ended up making a worse version of rigidbody. 😅 Would you advise using built in colliders and rigidbodies in the long run, I have heard some bad things about tilemaps but I am really not sure about the best way of adding physics.

rich adder
bright nexus
bright nexus
rich adder
#

and i usually lock all the constraints of the rb if im controlling it

#

depends if you want the built in gravity or not

bright nexus
#

Got it. Thank you for the time and help! I will probably continue with this method to experiment and see how things work out 😄

rich adder
#

goodluk 🙂

dense root
#

So I've been tinkering with this PONG project I have, I learned how to switch colors, more about RigidBodies and Colliders... what do you think I should tinker with next?

fossil drum
dense root
#

I want to do breakout but I'm trying to avoid follow tutorials

#

I feel like I'm not learning just mimicing someone on a screen

timber tide
#

why would you need to follow a tutorial

#

make a bunch of blocks, if pong ball hits it then deactivate it

#

^ after your collide

fossil drum
#

Then add some health to some blocks that you need to hit more then once, then add some powerups, add some scoring/highscore, perhaps some UI, some levels. You can learn a lot by doing this.

dense root
#

Anyone know how to solve this weird physics issue in Unity where the ball randomly slows down?

#

Here's the settings

keen dew
#

Since it doesn't bounce realistically I assume you have some code that changes its direction on impact. The problem would be there.

eternal needle
#

That first bounce does look really weird as well, it suddenly gains a ton of speed

keen dew
#

and at a completely different angle

dense root
#

How do I destroy my brick object?

private void OnTriggerEnter2D(Collider2D collision)
{
    Destroy(this);
    Debug.Log("Hit Brick");
}
eternal needle
dense root
#
private void OnTriggerEnter2D(Collider2D collision)
{
    Destroy(GetComponent<Rigidbody>());
    Debug.Log("Hit Brick");
}
#

The script

eternal needle
#

Yea pretty much the instance of the script. If you want the destroy the whole gameobject, you pass in the "gameObject"

#

Passing in a component will destroy only the component

dense root
#

Is there a more efficient way to have a box collider that triggers and bounces the ball without setting "shadow" box collider underneath it?

#

I tried making two BoxCollider2D under the same inspector window but that doesn't do the trick

keen dew
#

What's the problem you're having with just one normal collider?

dense root
#

It ghosts through the object since I need it to trigger

keen dew
#

Why do you need it to trigger?

dense root
#

OnTriggerEnter2D

keen dew
#

You do know there's OnCollisionEnter2D as well, right?

median ruin
#

How to fix? Is there a way to say which to always prioritize?

keen dew
#

Don't include the System.Numerics namespace

#

If you really need it (which I doubt) the last suggestion does what you asked

median ruin
#

thanks... can you disable auto imports?

keen dew
#

I'm sure there's a setting for it

ruby python
#

Morning all. I'm having a little trouble figuring out something.

I have this little hierarchy and I need to grab all of the ConnectionPoint objects and throw them into GameObject[] newConnectionPoints

There are multiple rooms that are getting spawned at start up using the same hierarchy so need to apply this to all of them as they spawn in.

Could someone point me in the right direction please? 🙂

#

🤣

dense root
#

Turns out I can add two colliders and have it work as intended

keen dew
#

I still don't understand why you would need that

dense root
#

One to trigger, one to bounce the ball back. Simple.

keen dew
#

But why do you need a separate trigger collider? Why not use the normal collider?

dense root
#

Wdym normal collider?

keen dew
#

I mean the collider that isn't a trigger

#

If you think that you need to use OnTriggerEnter2D, non-trigger colliders have an OnCollisionEnter2D event that works exactly the same way

dense root
#

Sigh have it your way lol

private void OnCollisionEnter2D(Collision2D collision)
{
    hitCounter++;

    SpriteRenderer m_SpriteRenderer;
    m_SpriteRenderer = GetComponent<SpriteRenderer>();

    if (hitCounter == 1)
    {
        m_SpriteRenderer.color = Color.blue;
    }

    if (hitCounter == 4)
    {
        Destroy(gameObject);
    }

    Debug.Log("Hit Brick");
}
#

This is definitely more elegant I suppose

rare basin
#

This is code related channel

#

but this is a graphics pack

undone juniper
topaz mortar
#

what's the proper way to do this?

#

if I just do object loadCharacter;
I get this right below

eternal needle
eternal falconBOT
hidden path
#

where do i download assets for free ( context - i need a forest pack to make enviroment and it should be compatable with 3d urp )

hidden path
#

my bad

sonic remnant
#

I'm facing a challenging issue in Unity where my constructable objects are incorrectly allowed to be placed through 'Tree' tagged objects, despite having collision detection logic in place. Here's a brief overview:

I have a script attached to my constructable objects to control their placement in the game world.
The script includes an OnTriggerEnter method intended to prevent these objects from being placed through other objects, particularly those tagged as "Tree" or "pickable".
Despite the logic, the constructable objects are still being placed through the 'Tree' objects. I'm using tags to differentiate between 'Ground', 'Tree', 'pickable', and 'ghost' objects.

https://gdl.space/emeqenusej.cs

cosmic dagger
ivory bobcat
#

isOverlappingItems has two conditions for being false in exit

#

The second is likely occurring

#

You can work around this by possibly having a list of objects that you're overlapping with or checking on stay (there's a possibility that you'll be flagged not overlapping and be able to quickly place the object though with the second).

topaz mortar
#

I wanna check if my variable I'm getting from an API is a number, more specifically an int

Debug.Log(myDic["level"] is int); // returns false```
Is System.Int64 not an int? Any easy fix?
gaunt ice
#

int64 should be long

ivory bobcat
#

It isn't an Int32

uncut holly
#

what does it mean by a complier error?

vast vessel
#

Look on the bottom of your screen

#

The red text is an error

#

Click on the "console" tab to see the whole thing

#

You are missing a ";" at the end of a line in your code

#

@uncut holly

halcyon summit
#

Does anyone know how a class can reference a ScriptableObject defined in one of its sub-classes please?

uncut holly
vast vessel
uncut holly
#

hmmm i added the ; but it still give me complier error?

uncut holly
#

this is what it looks like now

vast vessel
vast vessel
#

Configure your IDE to do auto completion

#

VS has a unity option in its installer. You can install it if you have the exe file

#

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

uncut holly
modest dust
vast vessel
modest dust
modest dust
uncut holly
#

is the Debug.Log suppose to change color?

#

cos the coding between the unity tutorial and mine is extremely different even though the wording is the same

modest dust
#

Classes, methods, fields, attributes, etc, all have their own color

#

All depends on your IDE and settings

uncut holly
patent compass
#

hello, i keep getting this error CS1061: 'object' does not contain a definition for 'name' and no accessible extension method 'name' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) in line.
clone.Find(child.name);

doesnt object have a definition of name?

modest dust
#

Also object and Object are two different things

nimble scaffold
#

how to switch cameras only the duration of right click for my fps sniper cam

patent compass
modest dust
#

var here defaults to System.Object

#

this type does not have a definition for "name"

#

Write the type you want explicitly

patent compass
#

thanks

uncut holly
#

i have a question for update, so assuming that we did not imput any codes to stop the program (at least from updating), it will just repeat the same message forever?

modest dust
#

Update() runs every frame

#

As long as the GameObject which this script is attached to is active (or the component/script itself is active) it will run every frame

modest dust
nimble scaffold
#

ok

#

hey @modest dust i have used this method but in unity gamemode its not working

modest dust
nimble scaffold
#

wait then bro

fair gyro
#

noob question: why is my camera shaking? Im using FixedUpdate() and SmoothDamp() for the new position

modest dust
#

!code

eternal falconBOT
nimble scaffold
#
using UnityEngine;

public class CameraSwitch : MonoBehaviour
{
    public Camera normalCamera;
    public Camera sniperCamera;

    void Start()
    {
        
        normalCamera.enabled = true;
        sniperCamera.enabled = false;
    }

    void Update()
    {
        
        if (Input.GetKeyDown(KeyCode.Y))
        {
            SwitchToSniperCam();
        }

        
        if (Input.GetKeyUp(KeyCode.Y))
        {
            SwitchToNormalCam();
        }
    }

    void SwitchToSniperCam()
    {
        normalCamera.enabled = false;
        sniperCamera.enabled = true;
    }

    void SwitchToNormalCam()
    {
        sniperCamera.enabled = false;
        normalCamera.enabled = true;
    }
}



#

Caesar

modest dust
#

You have an y in between your if statements

nimble scaffold
#

sorry

#

removed

fair gyro
#

Nvm I fixed it changing to LateUpdate() 👍

modest dust
#

Errors / doesn't work as expected?

nimble scaffold
#

its not switching

nimble scaffold
rare basin
#

are the camera objects enablind/disabling when you press Y?

#

you know you have to hold Y in order for this to work

#

if you release immediately, it will switch to normal cam

nimble scaffold
#

the y was typo

#

oh that one

#

sorry

modest dust
#

You're using KeyCode.Y

nimble scaffold
#

too much y

#

sorry extremel sorry

rare basin
#

chill

fair gyro
#

lmao

nimble scaffold
#

Bro the code isn't working

#

i pressed Y

rare basin
#

put debug logs in there

#

see if it prints

#

as i said you need to hold Y in order of it to work

gaunt ice
#

try to hold down the y and see if the two camera enabled

rare basin
#

if you press once both methods gets triggered

nimble scaffold
fair gyro
#

try this maybe? Input.GetMouseButtonDown(1)

hexed terrace
#

You toggle one cam on, then immeidately after toggle the other cam on.. you won't see it happen

rare basin
#

did you attach the script on actual game object?

nimble scaffold
rare basin
#

well you have a lot of errors in the console

#

fix them first

fair gyro
#

u changed to a different Input system in ur game

hexed terrace
#
private void Update()
{
    if (Input.GetKeyDown(KeyCode.Y)) { ToggleCameras(); }
}

private void ToggleCameras()
{
    normalCamera.enabled = !normalCamera.enabled;
    sniperCamera.enabled = !normalCamera.enabled;
}```
fair gyro
#

to use controller i guess

nimble scaffold
#

wdym sodio

rare basin
#

i assume you downloaded some project that is using new input system

modest dust
rare basin
#

and you made your own script using old input system

hexed terrace
nimble scaffold
rare basin
#

and it's using new input system probably

#

any your code uses the old input system

#

also you have errors in your Gun script

fair gyro
#

u are using this in ur project

#

so the way of coding changes a bit

nimble scaffold
#

yes

fair gyro
#

search for tutorials or ask github copilot/ chatGPT about the new Input System

nimble scaffold
modest dust
#

Especially to someone who is an absolute beginner

rare basin
#

chat gpt prints so many bullshit and bad practices

#

this is code related channel

peak crescent
#

ok

hexed terrace
nimble scaffold
#

guide me

peak crescent
fair gyro
rare basin
#

sure but why should he learn bad practices?

fair gyro
#

using AI is nice as long as u understand what are u coding, im not talking about Ctrl+c ctrl+v

modest dust
hexed terrace
rare basin
#

I'd argue about that

#

talking to @fair gyro

fair gyro
#

where should he learn from then...?

rare basin
#

where did you learn from before AI storm?

hexed terrace
#

The plethora of non-AI related places?

rare basin
#

weird question

modest dust
fair gyro
#

I learned from researching a lot of tutorials, stack overflow threads...

twin axle
#

I'm in college rn and we're not going to be learning unity, I'm not in game development though :3
I have picked up unity 2 days ago and I'm tryna do somethin as a side project.
I want to make my dev portfolio a game that you can play, amd navigate a little city to see my accomplishments. Let the journey begin

rare basin
#

i personally only use chat-gpt to make math formulas or physics operations

fair gyro
#

learning from what other people do

nimble scaffold
fair gyro
#

If u are worried about "bad practices" just go to college lol

twin axle
#

My teachers are horrible T_T I think they use gpt lmao

fair gyro
#

Im ending computer engineering grade and we didnt learn unity neither

nimble scaffold
#

will anyone help me?? its totally damn new

uncut holly
#

im using unity cos my freind wants to build a card game and im interested in vid game dev

twin axle
#

Ah, yeah I'm in comp sci. I pretty much wanna make my portfolio like old school runescape type deal poi t and click with the same shitty graphics, that I find nostalgic. It's gonna be a whole endeavor.

fair gyro
twin axle
#

Sorry I'll let everyone else ask questions :p gl out there

rare basin
modest dust
#

Will make things easier

uncut holly
#

holy shit the frames are fast

#

i just finished a code that expand a sphere and even after i used 0.001 for all 3 xyz the sphere took up the whole screen in less than 3 seconds

fair gyro
#

because Update() uses ur framerate

modest dust
uncut holly
uncut holly
#

take things nice and slowly

gaunt ice
#

you should turn it to time based not frame based
ie extend the ball in rate of 1m/s not 1m/many frames
you will learn it someday

nimble scaffold
#

im feeling to do suicide

modest dust
uncut holly
#

welp its not me but my brother who i share a body with but damm that hurt

fair gyro
#

@uncut holly do u make music too

uncut holly
fair gyro
#

i was just curious

modest dust
uncut holly
#

im working on an piano ost

fair gyro
#

I do background music sometimes too

hexed terrace
#

keep it on topic

uncut holly
uncut holly
modest dust
modest dust
solid jasper
#

is instantiating c# objects within a monobehaviour good practice? i.e. Dog dog = new Dog()
I don't know what to look for in the profiler to tell me whether this would have an impact or not, also the profiler seems to run "too fast".

static cedar
#

For clarification, does Dog inherit Monobehaviour?

solid jasper
#

Sorry edited post to remove double negative

#

Dog being just a regular csharp class not inheriting from anythign

static cedar
#

Ah, so you just mean literally make new objects in a method of a monobehaviour class.

solid jasper
#

yeah

gaunt ice
#

sometimes you must do that

static cedar
#

I don't see anything inherently bad with that. Doing it in Update is an obvious no-brainer.

#

Or FixedUpdate.

solid jasper
#

I see. So for context, I've been learning some design patterns with C# and tried implementing the Strategy pattern in Unity. Most examples don't use Monobehaviour so I've been trying to get my head around how I could use it.

gaunt ice
#

whether the class is monobehaviour or not has nothing to do with strategy pattern

wintry quarry
solid jasper
#

I get that, but it seems that the more I try to use just regular c# the more i move away from using the editor and inspector. I mean, yeah that makes sense, but it's messing with my head >.<

wintry quarry
#

You're overthinking it

solid jasper
#

You're right, I am

timber tide
#

imagine trying to construct prefabs in code

gaunt ice
#

you can even have a static class:

public static class Solution{
  public static result Solve(data){
    if(data is A){run A algorithm}
    else if(data is B){B algorithm}
    ...
  }
}
timber tide
#

So basically this pattern is how-to interface/pointers

#

I'm bad at reading these diagrams. They all remind me of creating data bases and that scares me

static cedar
#

Brackets not necessary if you inline them. UnityChanThink

slender path
#

does anyone know how to make destructible terrain?

wary sigil
#

hi wanted to save a text i input into a field to a json file The input and realted variable does work but i have some problems regarding the saving part, can anyone help?

wary sigil
#

the save file does not contain the text saved in inputText

ruby python
#

Af'noon all. Okay, so I'm building myself a simple map generator and I'm running into an issue where new 'rooms' are being placed 'over' ones that are already placed. I know why it's happening, and what I need to do to 'fix' it, but not sure on the how. What I think I need to do is run a check on whether the new room is 'inside' the old room and if so, remove it, but I want to keep everything inside this one script if possible. Just not sure how to implement it from here. 😕 Could anyone help out please?

rich adder
wary sigil
#

no

rich adder
#

characterCreation is probably blank

#

empty

#

how do you call InputName

wary sigil
#

but in the Debug.Log in InputName it says the correct thing

wary sigil
rich adder
wary sigil
#

using a button and On click event

gaunt ice
#
for (int i = 0; i < iterations; i++){
    connectionPoints = GameObject.FindGameObjectsWithTag("ConnectionPoint");
    foreach (GameObject connectionPoint in connectionPoints){
      GameObject newRoom=Instantiate(roomPrefabs[Random.Range(0,roomPrefabs.Length)],connectionPoint.transform.position,connectionPoint.transform.rotation);
      Destroy(connectionPoint.gameObject);
    }
}
```all connection points will be found in first iteration, meaningless to have several iteration unless some roomPrefab comes with connection point, and point back to some directions that having room on it
ruby python
#

Each prefab that gets instantiated has it's own connection points.

gaunt ice
#

oh, it is not destroy immediate

wary sigil
#

found another way it works i just added the part from FinishCharacterCreation to InputName

ruby python
#

so more are created each iteration.

gaunt ice
#

same set of connection points will still be found in next iteration, then prefab overlaps each others

ruby python
#

huh? But they're being dstroyed before the next iteration.

gaunt ice
#

you can try to log the connection points instance id to see if my point is correct
all destroy call will be queried until end of this frame, unless you call destroy immediate

wary sigil
#

ik but i somehow have to get it to work

#

already stared at that problem for three houres

neon ivy
#

I'm working on dialogue choices using Ink. when dialogue has choices I instantiate choice buttons and do:

choiceObj.GetComponent<Button>().onClick.AddListener(() => MakeChoice(choiceIndex));
``` to add the on click event to them. this is resulting in a `Exception: choice out of range` error and when I hover the buttons it says the On Click events are empty. does anyone know what's going on?
gaunt ice
#

commo mistakes (and trap)

#

you have to cache the choiceIndex to local variable

rich adder
ruby python
#

All the connection points are being removed as intended.

neon ivy
ruby python
#

(Disabled one are disabled in the prefab and never referenced)

neon ivy
#

do I need to do choiceIndex = new int(i)?

rich adder
#

instead of doing this contraption and getcomponent

neon ivy
#

no clue, following a tutorial but it has a max amount of buttons which I didn't like so I just instantiate them into a vertical layout group

rich adder
#

its not that diffcult mate

#

creating a class should've been first thing you learned lol

neon ivy
#

I mean sure it could work but I don't know if it's better is what I mean

rich adder
#

I think so 🤷‍♂️

gaunt ice
#

i have thought if this is possible:

struct somename{
  int idx;
  theMonobehaviour instance;
  public subscribe_this(){
    instance.method(idx);
  }
}
then
for(int i=0;i<number;i++){
  create a new somename struct and store it somewhere
  button[i].onclick.addlistener(somename.subscribe_this);
}
```i just take out the compiler's work, but i havent tested it.
neon ivy
#
private void DisplayChoices()
    {
        foreach(GameObject choice in choiceList)
        {
            choiceList.Remove(choice);
            Destroy(choice);
        }
        List<Choice> choices = currentStory.currentChoices;
        for (int i = 0; i < choices.Count; i++)
        {
            int choiceIndex = i;
            GameObject choiceObj = Instantiate(choicePrefab,choiceHolder.transform);
            choiceObj.GetComponentInChildren<TextMeshProUGUI>().text = choices[i].text;
            choiceObj.GetComponent<Button>().onClick.AddListener(() => MakeChoice(choiceIndex));
            choiceList.Add(choiceObj);
        }
        if(choiceList.Count > 0)
        {
            StartCoroutine(SelectFirstChoice(choiceList[0]));
        }
        
    }

    public void MakeChoice(int index)
    {
        currentStory.ChooseChoiceIndex(index);
    }

this is the entire code that gets called when the next dialogue gets called

rich adder
#

yeah that is ugly af

#

GameObject is a useless class type

#

this can be hadled with 1 Init() method in a custom button class

neon ivy
#

yea I have no idea what you mean by that :I

rich adder
#

example if you spawned choiceObj as its own thing ChoiceObject choiceObj = Instantiate(...) ; choiceObj.Init(index, text, somethingelse)

#

then make custom Action event, for button so you only keep a list of active buttons

neon ivy
#

UnityChanThink all that just because AddListener is being annoying?

ruby python
#

Okay now I'm confused. Just went through all of my instantiated prefabs, and at some point during the loop(s), the connectionPoints stop being destroyed 😕

rich adder
#

i stick to c# ones 😅

ruby python
#

??? 😕

rich adder
# neon ivy <:UnityChanThink:885169594560544800> all that just because AddListener is being ...

how I would do it

public class ButtonDialogue : MonoBehaviour
{
    [SerializeField] private Button button;
    [SerializeField] private TMP_Text txt;
    private int index;

    public Action<int> OnButtonPressed;
    public void Init(string text, int index){
        this.index = index;
        txt.text = text;
    }
    private void OnEnable() => button.onClick.AddListener(OnPressed);
    public void OnPressed() => OnButtonPressed?.Invoke(index);
}```
neon ivy
#

ah like a constructor

novel shoal
rich adder
# neon ivy ah like a constructor
ButtonDialogue choiceObj = Instantiate(choicePrefab,choiceHolder.transform);
choiceObj.Init(...)
choiceObj.OnButtonPressed += MakeChoice;
currentChoices.Add(choiceObj);```
maybe you can keep track also in a list for deletion / usubscribe
`List<ButtonDialogue> currentChoices = new();`
novel shoal
ruby python
#

@novel shoal switch the order of your destroy statements. You're killing the current object before it can destroy the other one.

gaunt ice
#

how about rigidbody

ruby python
#

Destroy(gameObject) should be last.

novel shoal
#

okk

ruby python
#

Putting it first means that you're removing the script before anything after it can be ran, so those lines no longer exist.

novel shoal
#

still not working

gaunt ice
#

do one of them have a rigidbody on it?

novel shoal
#

the "other" gameobject passes through the gameobject

novel shoal
rich adder
#

2d or 3D?

ruby python
#

One of them HAS to have a rigidBody for physics to work.

gaunt ice
#

they need a rigidbody.....

novel shoal
#

isn't rigidbody used for physics stuff?

rich adder
#

no rigidbody = no events

novel shoal
rich adder
ruby python
#

Doesn't matter.

novel shoal
#

okk

rich adder
#

OnTriggerEnter is a physics callback

#

Colliders are physics

#

Triggers are physics

gaunt ice
#

Note: Both GameObjects must contain a Collider component. One must have Collider.isTrigger enabled, and contain a Rigidbody. If both GameObjects have Collider.isTrigger enabled, no collision happens. The same applies when both GameObjects do not have a Rigidbody component.

novel shoal
ruby python
#

the 'other' object

gaunt ice
#

either one or both, up to your choice

rich adder
novel shoal
#

now it works, thanks :)

#

i am doing the junior programmer pathway unit 2 btw

ruby python
#

Okay, this is really really confusing.

I don't understand why my 'Destroy(connectionPoint.gameObject)' stops working partway through the room Instantiating loop. It's not at a fixed point either, if I increase the iterations it stops working further and further down the line 😕

https://pastebin.com/2vqHRt3f

neon ivy
neon ivy
#

wait nvm. I'm dumb. there's a known issue in the comments...

ruby python
amber spruce
#

is there a way to do smth when a object goes to a new scene (i have dontdestroyonload for them)

gaunt ice
rich adder
amber spruce
ruby python
rich adder
amber spruce
amber spruce
#

so when scene A is loaded do this

gaunt ice
#

in short
destroy a gameobject will not destroy it immediately

ruby python
#

Yeah, but I don't see why my code stops destroying the connection points, I've tried DestroyImmediate too and still the same thing.

#

!code

eternal falconBOT
drowsy fox
amber spruce
rich adder
ruby python
#

See this, makes perfect sense to me, find connectionPoint, spawnRoom, destroy connectionpoint, move on to next connection point. When finished all connection points found in the previous iteration of the forLoop, move on to the next iteration, rinse repeat.

What I don't understand is why it stops destroying the connectionPoints but keeps instantiating rooms.

for (int i = 0; i < iterations; i++)
        {
            connectionPoints = GameObject.FindGameObjectsWithTag("ConnectionPoint");

            foreach (GameObject connectionPoint in connectionPoints)
            {
                GameObject newRoom = Instantiate(roomPrefabs[Random.Range(0, roomPrefabs.Length)], connectionPoint.transform.position, connectionPoint.transform.rotation);
                //Debug.Log(connectionPoint.transform.name);
                DestroyImmediate(connectionPoint.gameObject);
            }
        }
amber spruce
wintry quarry
# ruby python See this, makes perfect sense to me, find connectionPoint, spawnRoom, destroy co...

https://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html

This function should only be used when writing editor code since the delayed destruction will never be invoked in edit mode. In game code you should use Object.Destroy instead.

Also note that you should never iterate through arrays and destroy the elements you are iterating over. This will cause serious problems (as a general programming practice, not just in Unity).

gaunt ice
#

suppose you have two prefab
Ac and c where c is the connection points
B
the A and B were spwaned as:
Ac
B
now two c (connection points) overlap

ruby python
#

If it stopped at the same point no matter how many iterations I enter into the 'iterations' variable, I could understand it, but it stops further and further down the line the higher the iteration count.

topaz mortar
#
while (reader.Read())
{
    myDic.Add("level", (int) reader.GetValue(1));```
Is there a way to provide the name of the column instead of 1?
ruby python
ruby python
gaunt ice
#

you have to check it just as what i said, the connection points may overlaps

wintry quarry
rich adder
wintry quarry
#

don't use FindWithTag
don't destroy things in a list you're iterating over.

modest barn
#

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

rich adder
#

if you're confused on the code I suggest you at least study up on what an event is @amber spruce

#

especially if you are needing one

topaz mortar
ruby python
#

This is so annoying. lol. Literally nothing I've found online does what I want.

gaunt ice
#

actually you can consider this:

Queue<Coonection point>
for iteration{
  int count=q.count;
  while(count>0){
    dequeue the connection point, spawn the prefab on it, then get all the connection points on that prefab and enqueue them
    count--;
  }
}
rich adder
polar acorn
buoyant knot
gaunt ice
#

and you need to check if some very close connection point has already enqueued

rich adder
gaunt ice
#

bfs