#💻┃code-beginner

1 messages · Page 1 of 1 (latest)

ivory bobcat
#

You'll need to provide more detail.

twin ibex
#

ok

static blaze
#

do a nullcheck on the script that's accessing the enemy object

twin ibex
#

this error appears after i aded a enemy spawners
so when the player kill the first enemy the error appear and the Spawnerrs didint work

static blaze
#

Well then you should probably put a prefab in the spawner instead of the enemy itself?

static blaze
#

Anyhow, sharing the code will always get you better help

#

im just guessing in the dark now

twin ibex
twin ibex
#

some help (;

ivory bobcat
#

Maybe show some code?

twin ibex
ivory bobcat
twin ibex
#

(:

ivory bobcat
twin ibex
#

@ivory bobcat
no i mean

#

the enemy is prefab now ok

#

do u understand me ?(:

ivory bobcat
#

Usually, you'd show what you've tried and people would give you suggestions.

twin ibex
#

i wasted 1H

#

for this error

uncut shoal
#

?

uncut shoal
uncut shoal
#

it is in the code.

#

The error you sent can only be caused by a problem in your code.

cosmic dagger
toxic void
#
x = (gameObject.transform.position.x < 0)? gameObject.transform.position.x -0.5 : gameObject.transform.position.x + 0.5;

how can I type cast this into a float?

#

like how do you use type casting with the ?: operator

cosmic dagger
#

do you know how to make a float value? if not, i'd look it up, it's quite simple . . .

toxic void
#

but I need to return it as a vector

#

oh wait nvm

#

I was missing suffix

#

I forgot

cosmic dagger
#

huh? you just asked about a float value, not it's supposed to be a Vector3? you're only assigning the value to x which i assume is a float . . .

cosmic dagger
toxic void
#

ye ye im stupid

vague socket
#

Hello, I'm fairly new to unity and I've just designed an enemy that detects if the player is in range and starts exploding once it's detected a player.

The enemy object currently has a polygon collider for it's hit box and a circle collider set to is trigger for detecting the player.

The problem I'm facing currently is that when circle collider is acting as a hit box as well. I read online that I should move the circle collider to an empty child object. My question is do I need to write a separate script for the child object or is there a way for the parent object to read the ontriggerenter of the child object.

Sorry if this is confusing and long 💀

polar acorn
# vague socket Hello, I'm fairly new to unity and I've just designed an enemy that detects if t...

All colliders will become "part" of their nearest parent rigidbody. If a rigidbody object has a box collider, and a child object of that has a circle collider, an OnCollisionEnter script on the parent will fire if something hits the circle collider.

When a collision happens, the rigidbody component is the thing that calls the OnCollision functions, and it calls it on itself and the attached rigidbody of the collider it's interacting with (if it has one)

languid spire
vague socket
#

Thank you for your replies :).

summer stump
# twin ibex the error not in the CODE

Just wanna say, this is a very common code error. It is saying the CODE is trying to use the object after it has been destroyed (which can only happen through code or I guess if you manually delete the object from the scene view during runtime, which you should of course never do)....

languid spire
wispy bison
#

Hi guys, i have bought a pack named Low Poly Restaurant, did you know why i see all like this_

polar acorn
wispy bison
#

So how i can fix?

polar acorn
#

Use materials compatible with your render pipeline, or use a render pipeline compatible with your materials.

#

One of em has to change

wispy bison
#

Fixxed thank you

tacit river
#
private void OnCollisionEnter(Collision collision)
    {
        placement.CanPlace = false;
    }``` this is not doing anything when a collision happens, did i code it wrong?
polar acorn
ivory bobcat
nova gorge
#

Hi! Im a beginner and have some trouble with my start screen and buttons. I did an animation for the start screen and make the button to play the game but its not clickable?

#

When i try to click on the button the game screen closes

calm chasm
#

I'm having issues with an instantiated object not running its Start() and therefore getting NullReferenceExceptions later on in the same script (many many frames after the initial instantiation). I've read in multiple forums that Start() will always run for instantiated objects, so I'm a little confused here. Any clue on what might be happening? I can provide more info if needed

gaunt ice
#

show your !code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

polar acorn
gaunt ice
#

is the prefab is disabled by default, the start wont run iirc

calm chasm
# gaunt ice show your !code

Instantiation code on the player object

    //The class this is running on is not a child of Monobehaviour, it's just a standard C# class with a method named Start
    public PenFeatherShotBehaviour() : base()
    {
        actionBuffer = new Timer(0.05f);
        // PREFAB LOADING
        featherShotPrefab = Resources.Load<GameObject>("Entities/Player/FeatherShot/FeatherShot");
        emberCost = 0.5f;
    }

    public override void Start()
    {
        base.Start();

        pen.animator.SetTrigger("shoot");

        pen.SpendEmber(emberCost);
        // INSTANTIATION
        GameObject featherShot = GameObject.Instantiate(featherShotPrefab, pen.transform.position, Quaternion.identity, pen.transform.parent);
        Movement2D featherMovement = featherShot.GetComponent<Movement2D>();
        featherMovement.velocity = new Vector3(FeatherShotController.baseSpeed * pen.facing, 0, 0);
    }

** Start() of the parent of the parent class of FeatherShot (the prefab who's Start() is seemingly not running)**
The child classes all have a base.Start() on their own Start().

    public virtual void Start()
    {
        attachedHook = null;
        //VVV^BREAKPOINT HERE DOES NOT RUN WHEN FEATHERSHOT IS INSTANTIATED!! VVV
        Transform hurtboxTransform = transform.Find("Collision/Hurtbox");
        //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        // [More irrelevant code here that is never being run]

        //This variable is not being initialized on FeatherShot
        immunityTimers = new List<(Timer, Immunity)>();
        stuckTo = false;
    }
calm chasm
calm chasm
#

I understand that's how it's meant to work but clearly I'm doing something wrong 🤣

#

Wait, actually, might have spotted it

cosmic dagger
#

are you calling Start anywhere?

gaunt ice
#

who calls start? this is no monobehaviour

cosmic dagger
#

if the parent class is not a MonoBehaviour, you need to call it, Start, manually . . .

calm chasm
#

regardless it seems I've spotted the issue, and the breakpoint was working after all

#

I'll pick it up from there, thanks!!

cosmic dagger
gaunt ice
#

i think you should share the code on featherShot(?) indeed, you say the NRE happens in that script not the instantiate script

calm chasm
gaunt ice
#

maybe the getcomponentsinchildren throws exception cause the start method is not "fully" executed

calm chasm
#

The GetComponentsInChildren is within the Start that's not fully executing, so anything it needs to run is already initialized by then
Is there a way for me to see exceptions being thrown by a specific line while step-by-step debugging? My log is being flooded by the aforementioned NRE

#
 public virtual void Start()
    {
        attachedHook = null;

        Transform hurtboxTransform = transform.Find("Collision/Hurtbox");
        if (hurtboxTransform != null)
        {
            hurtbox = hurtboxTransform.GetComponent<Rigidbody2D>();
        }
        else
        {
            hurtbox = null;
        }

        boundsExtents = Vector3.zero;
        boundsOffset = Vector3.zero;
        
        Collider2D[] colliders = hurtboxTransform.GetComponentsInChildren<Collider2D>();
  // STOPPING HERE
        if (colliders.Length > 0)
        {
            Bounds bounds = new Bounds();
            bounds.center = (Vector3)colliders[0].offset + transform.position;
            bounds.Encapsulate(colliders[0].bounds);

            for (int i = 1; i < colliders.Length; i++)
            {
                bounds.Encapsulate(colliders[i].bounds);
            }
            boundsExtents = bounds.extents;
            boundsOffset = bounds.center - transform.position;
        }

        immunities = new List<Immunity>();
        immunityTimers = new List<(Timer, Immunity)>();
        stuckTo = false;
    }
gaunt ice
#

i remember there is a error pause button on console, turn on it

#

the hurtboxtf maybe null and you call a getXXX method on it

cosmic dagger
calm chasm
#

That's it, I forgot to add my hurtbox to the dang projectile

#

Tyvm

gaunt ice
#

he uses find to find that tf

cosmic dagger
#

if it's null, hurtbox will not be asigned and execution continues and tries to access it on the line before it stops . . .

#

when ever you get an NRE, look at the all the reference variables on the line and check they have a value (are assigned) . . .

cosmic dagger
cosmic dagger
calm chasm
#

I'm using all the finds to avoid drag and drop

#

I just forgot that some objects will not have hurtboxes, such as this projectile, and needed to add additional checks for that

polar acorn
cosmic dagger
gaunt ice
#

try to not use find, drag and drop can guarantee the component is assigned

calm chasm
#

I see, I see. I'll get to refactoring that, since there's few objects to change, then

cosmic dagger
#

you can have a check to assign a value if it is null (meaning it wasn't assigned a value from the inspector . . .

gaunt ice
#

btw it will throw an unassigned exception if you have not assign it

river glade
cosmic dagger
river glade
#

done

#

sorry, my mistake

cosmic dagger
#

not a problem, just helps to see what is going on easier . . .

river glade
#

yes , ty

cosmic dagger
#

Lerp is used incorrectly. when using Lerp is good to use a duration. to animate linearly. you can also use MoveTowards, i think they have a Vector3 option . . .

river glade
#

should I use a target in the " endPosition " position?

cosmic dagger
#

the end position is your destination . . .

#

the third value for Lerp, *t*, should be animated from 0-1, typically, determined by the elapsedTime/duration. elapsedTime is added to every frame . . .

languid spire
#

also, the yield is outside of the while so the Lerp is moot

cosmic dagger
#

yep, and the !open doesn't Lerp at all, it just sets the position . . .

languid spire
#

and it's an infinite loop

river glade
#

basically everything was wrong lol

languid spire
#

yes

summer stump
#

And there is a bit too much whitespace

Sorry, just teasing.

cosmic dagger
#

but it's a work in progres, so . . .

#

i wanted to speak on the whitespace but declined myself . . .

river glade
#

the white space is due to the fact that I deleted a lot of things and quickly copied and pasted them into pastebin, it's still a work in progress ahah

languid spire
#

Hey, he can have as much whitespace as he wants, it will neither generate a compile nor runtime error

#

That is the least of his worries

cosmic dagger
#

true, i just hate scrolling . . .

#

that's a me problem though . . .

river glade
#

I'm simply learning programming, peace and love haha

cosmic dagger
languid spire
summer stump
#

I was just teasin, no need to worry about that at all, like steve said

river glade
cosmic dagger
cosmic dagger
languid spire
cosmic dagger
river glade
river glade
cosmic dagger
river glade
languid spire
cosmic dagger
#

oh, that's like a dedicated unity layout, nice!

languid spire
#

Works for me

cosmic dagger
#

i think 3 across: landscape, landscape, portrait, with a 4th above the middle would work perfect for me. i'd need a different monitor arm though . . .

languid spire
#

tbh I tried multiple vertical monitors, didn't like it, neck strain, horizontal works better imo

#

plus the mouse movement is really weird using multiple verticals

cosmic dagger
#

especially, if you sit close to the desk . . .

queen adder
#

When i create a variable that has a type of "System.Action", the compiler tells me to convert that into a local function like this:

public void Method()
{
  System.Action variable = () => cute();
  // After i listen to the compiler:
  void variable() 
  {
     cute();
  }
}

Which one is more efficient way for Garbage and performance

woeful hedge
#

What should I do to execute Multiple gameObjects Component's function which have same name?
Like BroadcastMessage() but can use outer Gameobject and its child.

yep I could just grab them to large List<> but I dont want em

swift crag
#

I would just make explicitly make a list once and then use that list every time i need to call the methods

polar acorn
cosmic dagger
woeful hedge
polar acorn
woeful hedge
#

I hate you dyno

#

Anyways Thanks for answer :)

twin ibex
#

Hi
i have a problem with the Enemy in the game
When the Player kill the Enemy the console shows a error
THe error 👇

Your script should either check if it is null or you should not destroy the object.```
polar acorn
twin ibex
#

so What's the solution ?

twin ibex
polar acorn
#

This is really all that can be answered with no context

#

Somewhere you're referencing something that no longer exists, stop doing that

twin ibex
polar acorn
polar acorn
#

I have no idea what your system looks like

#

I don't know what reference is being destroyed

twin ibex
#

i will show u

twin ibex
polar acorn
zealous oxide
#

evening friends. i've got a transform in here on an enemy spawner but the transform doesnt update, despite the object that was dragged into the field having moved (its always to the right, relative to the player). is there some way i can force update the transform

polar acorn
twin ibex
#
using System.Collections.Generic;
using UnityEngine;

public class SpownSystem : MonoBehaviour
{
    public Transform[] spawnPoints;
    public GameObject Enemy;
    int randomSpawnPoint;

    void Start()
    {
        InvokeRepeating("SpawnEnemy", 0, 1.5f);
    }

    void SpawnEnemy()
    {
        randomSpawnPoint = Random.Range(0, spawnPoints.Length);
        Instantiate(Enemy, spawnPoints[randomSpawnPoint].position, Quaternion.identity);
    }
}



polar acorn
twin ibex
#

first i try to make the enemy a prefab but the error is keeps appearing

#

now its not prefab

#

but nothing changes

polar acorn
twin ibex
#

the enemy itself

polar acorn
twin ibex
#

the spawner cant make more clone

languid spire
#

show the code that is doing the Destroy

twin ibex
polar acorn
# twin ibex i know

So why are you spawning an object that can be destroyed, instead of a prefab

twin ibex
polar acorn
twin ibex
# languid spire show the code that is doing the Destroy
private void OnCollisionEnter2D(Collision2D collision)
    { 
        if (collision.gameObject.CompareTag("Bullet"))
        {
            Instantiate(Explosion, transform.position, Quaternion.identity);
            Destroy(collision.gameObject);
            Destroy(gameObject);
        }
    }
}```
twin ibex
#

??

polar acorn
twin ibex
zealous oxide
polar acorn
twin ibex
#

seee
the enemy is prefab

polar acorn
#

You have to drag in the prefab into the spawner's variable

twin ibex
#

yes?

polar acorn
twin ibex
twin ibex
polar acorn
# twin ibex

Okay, so, Enemy is a prefab. That means the error can't be coming from Enemy being destroyed

twin ibex
#

?

polar acorn
#

The error isn't coming from Enemy being destroyed. It's somewhere else.

twin ibex
#

from where

twin ibex
languid spire
#

show the COMPLETE error

twin ibex
#

ok

polar acorn
twin ibex
# languid spire show the COMPLETE error

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, UnityEngine.Vector3 pos, UnityEngine.Quaternion rot) (at <6c9b376c3fca40b787e8c1a2133bf243>:0)
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <6c9b376c3fca40b787e8c1a2133bf243>:0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <6c9b376c3fca40b787e8c1a2133bf243>:0)
SpownSystem.SpawnEnemy () (at Assets/SpownSystem.cs:19)

cosmic dagger
#

still the same error . . .

zealous oxide
rich adder
#

doesnt this mean they referenced a destroyed object they added in the inspector and trying to spawn it

polar acorn
twin ibex
languid spire
#

I wonder if it is a spawnPoimt which has been destoyed

polar acorn
#

Because the line numbers don't lie

twin ibex
twin ibex
rich adder
polar acorn
twin ibex
polar acorn
twin ibex
#

oh

#

what code the spawner code?

rich adder
#

SpownSystem prob

twin ibex
polar acorn
polar acorn
# twin ibex

So, it's possible that an element of spawnPoints was destroyed. Are any of them ever destroyed?

#

But let's first make sure. Can you show a screenshot of the thing you dragged into the Enemy variable on this script

#

What was the thing you clicked on and dragged into the slot

chrome scarab
#

Hello, in this following code:

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (isAttacking || isAttacked)
        {
            if (collision.CompareTag("Enemy"))
            {
                damage = 10f;
                enemyHealth = collision.GetComponent<EnemyHealth>();
                enemyHealth.DamageEnemy(damage);

                if (enemyHealth.enemyHealth <= 0f)
                {
                    Animator enemyAnimator = collision.gameObject.GetComponentInChildren<Animator>();
                    enemyAnimator.SetBool("Die", true);
                    //wait
                    Destroy(collision.gameObject);
                    killedEnemies += 1;
                }
            }
        }
    }

I want to add something to the //wait section that will make it wait for 1.5f seconds. How can I do this? The reason I want this is to wait for the death animation to end instead of destroying the gameobject instantly.

polar acorn
wintry quarry
polar acorn
#

You can just have the destroy happen after some amount of time

wintry quarry
#

Or these ^

chrome scarab
polar acorn
#

Yes

chrome scarab
#

oh tyvm

twin ibex
zealous oxide
#

Right after spawning the enemy put this

chrome scarab
# polar acorn Yes

Why does it tell me to remove it when I get to this line? it was doing this a while ago, I don't understand why...

twin ibex
#

@polar acorn

polar acorn
# twin ibex

Which thing did you drag in. This is very important

chrome scarab
polar acorn
chrome scarab
twin ibex
polar acorn
ivory bobcat
rich adder
twin ibex
chrome scarab
polar acorn
#

What thing did you click your mouse on and then move to the slot

twin ibex
#

ohhhh

polar acorn
#

fucking

#

one

chrome scarab
polar acorn
#

I'm not going to ask again

#

what thing

#

did you click on

#

to drag

#

into the slot

languid spire
#

before you answer, there are 2 enemies on the screenshot you sent

twin ibex
#

can i send a vedeo

polar acorn
#

just show me

#

which Enemy

#

you drag in

chrome scarab
twin ibex
#

oh

#

im dumb

#

the num 1

rich adder
#

oof

chrome scarab
#

it's a gameobject

polar acorn
#

I asked you multiple times if you dragged in the prefab or the enemy in the scene

#

and every time

#

you said the prefab

chrome scarab
#

bruh

rich adder
#

yeah as soon as you hit play Prefab turns into GameObject

twin ibex
rich adder
summer stump
chrome scarab
twin ibex
#

bruuuuuuuuuuuh

lavish ginkgo
#

guys i redownloaded VS but my scripts arent working ?

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)

lavish ginkgo
twin ibex
#

tthx for the solution@rich adder@chrome scarab@summer stump@polar acorn

chrome scarab
#

u re velcome

twin ibex
#

@polar acorn
im SO VERY EXTREMELY SORRYfor my stupidity

chrome scarab
#

Which children does this get the tilemap component from?

tilemap = grid.GetComponentInChildren<Tilemap>();
chrome scarab
willow scroll
chrome scarab
willow scroll
#

otherwise you have to Find or FindGameObjectWithTag

chrome scarab
#
        foreach (Tilemap tilemap1 in grid.GetComponentsInChildren<Tilemap>())
        {
            if (tilemap1.name == "Zemin")
            {
                tilemap = grid.GetComponentInChildren<Tilemap>();
            }
        }

This was the first solution that came to my mind. but I didn't test it.

willow scroll
chrome scarab
rich adder
#

why dont u just put fields in the inspector?

#

GetComponentInChildren find the First component

chrome scarab
rich adder
#

what is this point of doing this..

willow scroll
rich adder
#

just un-necessary calls to GetComponent tbh

willow scroll
#

you assing tilemap to new GetComponentInChildren

#

you have to assign it to tilemap1 to make it work

rich adder
#

you cant change it during a foreach loop

cosmic dagger
rich adder
willow scroll
rich adder
#

like an inspector field i meant

willow scroll
rich adder
willow scroll
rich adder
#

I know I said that

chrome scarab
# rich adder uhh the same way you did `Grid`

The reason I do this is because I need to select a tilemap in another script. and I need to select gameobject to select the tilemap. And when I select gameobject, I cannot apply to prefab.

willow scroll
rich adder
rich adder
chrome scarab
willow scroll
rich adder
olive wharf
#

I'm tryna recreate the circle illusion where the dots move in a straight line but it looks like a circle rolling. I've got it mostly down but I have an issue with how my dots are placed about; they make gaps instead of being evenly spread in a circle looking way:

using System.Collections.Generic;
using UnityEngine;

public class DotsManager : MonoBehaviour
{
    public GameObject dotPrefab;
    public List<GameObject> dots = new List<GameObject>();
    public int dotAmount;
    public float dotSpeed;
    public bool showLines;

    float angle;
    float turningAngle;

    void Start()
    {
        turningAngle = 0;
        dotAmount = dots.Count;
    }

    void FixedUpdate()
    {
        angle = 0;
        turningAngle += dotSpeed;

        for(int i = 0; i < dotAmount; i++)
        {
            dots[i].transform.position = new Vector2((Mathf.Cos(angle) * 3f) * (Mathf.Cos(turningAngle + angle)), (Mathf.Sin(angle) * 3f) * (Mathf.Cos(turningAngle + angle)));
            angle += (180 / dotAmount);
            print(angle);
        }
    }
}

If it helps, I have a scratch project that does this that I'm using as referenece https://scratch.mit.edu/projects/809102399/editor/

#

Can anyone figure out what I have done wrong

jovial peak
#

question, so im making an editor and implementing an undo redo function, how do i get the prefab used to create the object before it is deleted, so it can be undone?

rich adder
#

look into command pattern probably

jovial peak
#

thx ill have a look,

chrome scarab
#

Is there an easy way to find places where changes have been made? I've been browsing the inspector panel for 5 minutes...

queen adder
#

Overrides* tab when u click prefab in the inspector

chrome scarab
#

enemy list is the same too

wintry quarry
#

When you click the apply drop-down should show a list

chrome scarab
queen adder
queen adder
#

oh i get change for a reason though so forget it, never really checked on that haha

chrome scarab
queen adder
queen adder
queen adder
#

now ur Human is a prefab though so forget this but if ur human has a gun within his hierarchy, the gun is not necessarily a prefab, and if u run the game its all gameobjects

dusk minnow
#

Hey i need some help iam setting the color of a line renderer to a new Color(5,5,5,255) but it comes out different so the color is then like 200,200,200, 57 or smth why is that

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

dusk minnow
#

there is a list with colors and the tower laser (linerenderer) should first be the color of the list[0]

rocky canyon
#

colors use 0 - 1

dusk minnow
#

so 256 would be 0.0036565 something

#

or should i do 1/256

rocky canyon
#

theres a method to convert it directly

languid spire
#

just use Color32

rocky canyon
#

no need to figure out the math urself

dusk minnow
queen adder
#

Anyone knows how can i hide <summary> tags in vs code? they look so ugly

terse solstice
#

how can I give the illusion of walking by moving the first person camera

#

?

dusk minnow
#

i have reloaded a scene and all things got deleted how can i redo this

polar acorn
thin kiln
dusk minnow
polar acorn
thin kiln
final kestrel
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.EventSystems;

public class TextMaterialChange : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{

    [SerializeField] private Material hoverMaterial;
    [SerializeField] private Material originalMaterial;
    private TextMeshProUGUI textMeshPro;
    // Start is called before the first frame update
    void Start()
    {
        textMeshPro = GetComponent<TextMeshProUGUI>();

        originalMaterial = textMeshPro.fontMaterial;

    }

    // Update is called once per frame
    void Update()
    {

    }

    public void OnPointerEnter(PointerEventData eventData)
    {

        textMeshPro.fontMaterial = hoverMaterial;
    }

    public void OnPointerExit(PointerEventData eventData)
    {

        textMeshPro.fontMaterial = originalMaterial;
    }

}
``` this script is supposed to change to glow material when pointer enters. It was working yesterday but now my text just disappears when I hover over. I get no errors.
#

I assigned the materials in the inspector

ivory bobcat
final kestrel
#

yes it does

ivory bobcat
#

Have you tried other materials?

#

For the problematic one

final kestrel
#

I created another button and another material

#

It still does the same.

ivory bobcat
#

Have you tried a different material for the problematic one?

daring tundra
#

Does anyone know why my input could be delayed in low frame rates? Is there a common fix for this like multiplying by Time.DeltaTime?

polar acorn
final kestrel
ivory bobcat
polar acorn
final kestrel
#

If i manually put it on the text it disappears

ivory bobcat
polar acorn
final kestrel
polar acorn
#

The material is invisible for whatever reason

final kestrel
#

This is the material.

ivory bobcat
final kestrel
#

Ah all right. Thanks for the help

#

Uhh... Which channel do i ask on?

ivory bobcat
final kestrel
#

Ui ux?

#

Okay thanks

ivory bobcat
final kestrel
analog depot
#

hi there, dumb question, if I have a normalized vector3 and I want a world position from another object 2 units say in the opposite direction to that vector, what should I do?

#

pos here x >> obj >> vector ----->

daring tundra
#

And it is in FixedUpdate

ivory bobcat
polar acorn
analog depot
#

yea

polar acorn
#

position + (direction * -2)

analog depot
#
  • -2
#

?

#

perfecto sorry 🙂

#

yea that works great - thanks!

winged meadow
#

hi, how to make drop down folder like this by script ?

polar acorn
#

If you want a foldout without a list you'll need a custom inspector

winged meadow
polar acorn
winged meadow
royal ledge
#

I'm not sure this is the right channel but, when creating a game for pc, unity recommends using a 10.8 size camera importing sprites at 100 ppu for example. Does this mean my tileset should be 100x100 then? Or do games usually mix ppu's. Thanks in advance

sly wasp
#

I forgot, so what is the code to generate a gameObject into a tagged object?

cosmic dagger
sly wasp
true pasture
#

Is that what you mean?

sly wasp
true pasture
#

Yeah just look at the instantiate docs for the syntax

sly wasp
#

im meaning on putting it inside a tagged object
likke i need the script to find that

true pasture
#

Every object with that tag?

sly wasp
#

yea

true pasture
#

And just add the thing you want to each object in the array it returns

polar acorn
#

Like, at the same position?

sly wasp
#

same position

polar acorn
sly wasp
#

so how do i generate it inside every object with a tag ("obstacle")?

true pasture
#

It would be a child then not parent

sly wasp
#

oop

#

meant child sorry

#

but the array, do i do
public GameObject[] obstacles?

polar acorn
sly wasp
#

and then

obstacles = FindGameObjectsWithTags("obstacle");?

sly wasp
#

i meant the gameobject being a child of the tagged object

polar acorn
# sly wasp yeah

So, loop through a list of all objects with a tag, then spawn your object using the Instantiate overload that takes in a parent

sly wasp
#

GameObject[] obstacles;
obstacles = FindGameObjectsWithTag("obstacle");

But I am not very good at instantiating yet

true pasture
#

Its just a function theres no skill barrier lol

young grove
#

Input system is set to use both, but after I updated the package, I can't use old input system methods like GetButtonDown() how do I fix this?

young grove
#

Yes

polar acorn
#

What is it

young grove
#

Get button doesn't exist in input

polar acorn
#

Show code, show error

young grove
#

if (Input.GetButtonDown("Shift")

Input does not contain a definition for GetButtonDown

polar acorn
#

You have a class named Input

languid spire
#

or just a variable

young grove
#

No

#

Also side problem, the unity stuff doesn't show in vscode autofill and some of the csproj files show up as not supported by c# dev kit, it's no biggie but it is bothersome

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

polar acorn
#

Do you get the error in unity or just in the IDE

young grove
#

Seront in just unity

polar acorn
young grove
#

Also ide was fine a month ago when I last used it, idk y it stoped working right

young grove
polar acorn
#

Show a screenshot of it anyway

young grove
#

I renamed PlayersController to SplayerController now it's gone and working

#

IDK why coding is so random like this

#

How does renaming a file fix this issue? There completely unrelated

#

The error came from a complete other script

polar acorn
#

Renaming something recompiled it

young grove
#

It was saved I opened the project 2 min ago and changed nothing

#

All I did was rename this unrelated script and it works

#

Whatever if it works it works

#

But anyone know why vs code doesn't like the csproj files? It just bothers me the 33 by the red x on the bottom, also it would be nice for the autofill to work with unity methods, and yes I have the unity and c#dev kit extensions and vs code package on unity end

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

young grove
# polar acorn !ide

I have it set up exactly like this for vs code already and I double checked

young grove
#

ok all I did was update visual studio package and it made visual studio code work

#

apparently the visual studio code packahe is obsolete or something

#

are there any alternatives to mlagents

earnest goblet
#

um so my scene has merge conflicts that im not seeing on github desktop, do i have to use git to fix the merge?

silent valley
#

Hi. I'm trying out raycast and have managed to get it to work and to detect tags. I'm trying to make it so text pops up on screen. For example, if you're looking at a picture then the text "This is a picture" will pop up on screen.

ashen ferry
#

Ive got ui manager singleton controlling ui state on screen if u do that u just make public method there enabling ur text canvas and setting text element values in it then run it where u want

swift crag
jagged vortex
#

Guys what do I do if my camera is in the void basically and I cant get back up to the platform im working on

#

nvm I fixed tit

swift crag
#

setting its position directly in the inspector can help

#

if you've flung it out to a wild position

rapid mountain
silent valley
#

This is what I have managed to do. Only problem is if i walk backwards while I was looking at the picture. the text doesnt go away unless i go back to it and look away while i'm next to the picture

rapid mountain
#

its better to have a guard clause at the very start that only executes the rest of the code if the raycast has hit something, if not just return

silent valley
#

Could you explain what that is please?

rapid mountain
silent valley
#

Right, Gotcha. I'll save that for the morning. I appreciate the reply

eternal knoll
#

why am i getting an error here?

ivory bobcat
eternal knoll
#

i am just trying to call a function from another script

eternal knoll
ivory bobcat
ivory bobcat
#

Is the component called auth manager as well?

eternal knoll
#

they are all called AuthManager

#

i followed tutorials on yt but theirs work and mine doesnt

north kiln
ivory bobcat
eternal knoll
#

wait

#

wow

#

i didnt realize

eternal needle
half cosmos
#

yo wut does dis mean

#

everytime i try to make a project

#

it doesn't work

#

and i get this message

ivory bobcat
half cosmos
eternal knoll
#

both is set to if (task.IsFaulted) but one works and one doesnt

#

when the sign up is faulted, logText.text changes but when the sign in is faulted, logText.text doesnt change, even though they are the same script

#

when the first one is faulted, only debug.log(signin failed) works, the code logText.text = "password is incorrect" underneath doesnt work

wintry quarry
#

ContinueWith vs ContinueWithOnMainThread

#

You can't touch Unity objects from a background thread

eternal knoll
#

oh

#

wait lemme change

#

the first one to ContinueWithOnMainThread?

#

mb because i was copying this code online so i didnt notice

brazen veldt
#

you can get TMP_Text component with GameObject.GetComponent<TMP_Text>(), right?

#

i have, everywhere says it works and i get null

slender nymph
#

show the relevant code, the error + stack trace, and the object you are calling GetComponent on

brazen veldt
slender nymph
#

so if line 21 is throwing the NRE then the issue isn't the GetComponent call. it's that your GameObject.Find call is returning null

#

which means either that object does not exist in the scene at the time this code runs, it has a different name, or it is not active

brazen veldt
#

OOOOOOOh

#

did not know it needed to be active

slender nymph
north kiln
silent valley
#

I've been scraping my head with this one for ages. all I want is the text on the screen to go away as soon as I'm not looking at one of the objects. If I'm close to the object, it does disappear but if I'm on the edge of the raycast beam, it'll stay on my screen until I look at something else.

summer stump
wintry quarry
north kiln
#

Also, best to use CompareTag instead of equality to check for tags

summer stump
#

Also, I would do

if (picture)
Else if (chair)
Else if (table)
Else

Instead of the else after each if statement

#

Or a switch with a default for when you add more things

wintry quarry
#

or better yet just using the name or some string from a component directly rather than handling it all here.

north kiln
#

If we're gonna go all the way on suggestions, I would make the raycasting script perform no logic, and have it handled by a component on the objects through an interface

#

but it's complicated for beginners, so simple is fine

summer stump
#

Agreed. Didn't want to stray too far, but yes

silent valley
#

So what exactly is my problem here? I would of thought the else then the SetActive(false) would automatically disable the text when not looking at it

#

I probably sound stupid but I want to understand and not just nod my head not knowing whats going on.

summer stump
#

If (raycast)
All that stuff
Else
Set false

#

Because you can only get to your current code setting it false when the raycast SUCCEEDS against something that isn't those three things.

You also want it to set false when it fails (not pointing at anything)

silent valley
onyx ledge
#

Hi everyone, the code itself isn't that difficult, so I'm writing it here. How do I get GPGS services to work on iOS as well? iOS doesn't use Google Play Store, so I don't know how to develop it

summer stump
# silent valley The last part is what I have tried finding online for awhile. I found a few thin...

Just to be clear, I meant something like this. This is trying to keep it as close to how you have it as possible. Definitley not the best way. I would have the object have an interface like Vertx said and turn its OWN text on, but this is along the lines of how you have it, but what you need to fix it

if (Physics.Raycast(theRay, out RaycastHit hit, range))
{
  if (hit.collider.CompareTag("Picture")
  {
    picturetext.SetActive(true);
  }
  else
  {
    picturetext.SetActive(false);
  }
  if (hit.collider.CompareTag("Chair")
  {
    chairtext.SetActive(true);
  }
  else
  {
    chairtext.SetActive(false);
  }
  if (hit.collider.CompareTag("Table")
  {
    tabletext.SetActive(true);
  }  
  else
  {
    tabletext.SetActive(false);
  }
}

else
{
  picturetext.SetActive(false);
  chairtext.SetActive(false);
  tabletext.SetActive(false);
}
silent valley
#

Trying that now.(Just trying to fix errors about the compare tag) I also tried the last bit with the false' earlier.

summer stump
#

That should have worked. hmmm

silent valley
#

i only had 3 false' like yours at the bottom. you have them in the if too

summer stump
#

to show it clearly:

if (Physics.Raycast(theRay, out RaycastHit hit, range))
{
  // all the checks
}

else
{
  picturetext.SetActive(false);
  chairtext.SetActive(false);
  tabletext.SetActive(false);
}
#

the top if closes

silent valley
#

sorry. I've been at this since midnight. It's almost 7 am

vital shadow
silent valley
#

Well, right now. I'm trying to figure this out. But the original one is Raycast. I have it so when you look at an item, text appears on screen for what the item is etc. while looking at the item, if i walk back, the text still stays on my screen unless i look literally up to the sky or go onto another object. (range is 4).

north kiln
eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

summer stump
#

I'm a bit shot too, my code was messed up. I need to go to bed

vital shadow
#

Send me gui configuration

summer stump
#

You run CompareTag on the collider, not the tag (of course) headslap

summer stump
vital shadow
#

The configuration of the layout

silent valley
#

@summer stump I WOULD KISS YOU RIGHT NOW. Thank you so much. It works. Cry Cry Love

summer stump
silent valley
#

I'm going to study that code and compare it to my one. THANK YOU

vital shadow
#

Sorry boys

north kiln
silent valley
woeful hedge
#

Why my Unityevent can't send arguments well?

north kiln
woeful hedge
#

wait

#
        private void OnBlockStart(MidiData.MidiBlock block, int idx)
        {
            Debug.Log("Start Event Send =>" + idx);
            NoteStartEvent.Invoke(idx);
        }
        
        private void OnBlockEnd(MidiData.MidiBlock block, int idx)
        {
            Debug.Log("End Event Send =>" + idx);
            NoteEndEvent.Invoke(idx);
        }
#

ahhhh indent

#
    public void OnNoteStart(int noteidx)
    {
        Debug.Log("Note No." + noteidx.ToString() + "Start Received");
        changeScale(2);
    }

    public void OnNoteEnd(int noteidx)
    {
        Debug.Log("Note No." + noteidx.ToString() + "End Received");
        changeScale(1);
  
    }
north kiln
#

The subscription is what I need to see

woeful hedge
#

ohhh i see

#

Thanks

sacred reef
#

i want to change the cinemachine body from transposer to do nothing via code how to do that ?

obsidian jewel
#

hi every one.

#

i want to make some identification paper like paper please. i have some problem with that data type and do i need use object to make all of them

static cedar
#

What? UnityChanThink

obsidian jewel
obsidian jewel
#

so i just working with string and make some method to check?

rich adder
obsidian jewel
#

ok i will try.

open kernel
tulip nexus
#

any idea

slender nymph
#
  1. your last ) is in the wrong place
  2. you do not need to cast to GameObject when using Instantiate. that hasn't been necessary for like 4 years or more
unreal crown
#

How do I make OnPointerEnter work with Unity Visual Scripting? I have a Script Graph on an Image with that node, but it just doesn't trigger. I don't think it's a raycast issue, since that same graph has an On Mouse Input event that works just fine

slender nymph
unreal crown
#

...Can't believe I didn't notice that channel before. Thanks for directing me to it

cursive burrow
#

how to begin c# for unity

ivory bobcat
eternal falconBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

slender nymph
cursive burrow
#

thanks

slender nymph
#

personally, i recommend learning c# separately from unity then learning how to use it in unity

onyx prairie
#

Could someone explain to me why the if statement (if (currentWaypointIndex >= wayPoints.Length) does not immediately assign currentWayPointIndex to 0 when the maximum number of indexes of the wayPoints array is reached? Don't get me wrong, my code works completely fine, I just wanted to ask as why it is like that?

north kiln
#

If you're confused at how it's working you should use the debugger and step over your code to see it execute

sour fulcrum
north kiln
#

The logic is correct

sour fulcrum
#

Genuinely correct me if I'm wrong but would currentWaypointIndex == wayPoints.Length - 1 be more accurate since the check is specific to the actual logic your trying to check?

Right now from that code alone it looks like if it fails the check it's just going to ++currentwaypointindex until the if statement clears since that distance check is going to keep hitting true (unless some outside code is changing stuff)

north kiln
#

The problem is that there is no context to explain what they are doing or how they want it to work, but the logic is correct.

slender nymph
sour fulcrum
#

Heard

#

In theory the greater check will never run because the equal check will always reset it before that point, Right?

north kiln
#

Correct. Though, I generally perform checks like that too

#

if I do it that way all the time it saves the load to think about the other options if they're ever in my code

dusk minnow
#

Why is the privot of the tower back there?

ivory bobcat
slender nymph
#

this is a code channel. but also make sure that your tool handle is actually set to pivot and not center

vocal fable
#

why is there an error

slender nymph
#

what does the error say?

vocal fable
#

} expected

slender nymph
#

then you probably have a missing } somewhere

#

of course you aren't showing all of the relevant code here so i don't know why you expect anyone to just know that

vocal fable
#

no i dont have a missing }

slender nymph
#

show the code then

ivory bobcat
vocal fable
slender nymph
eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

vocal fable
slender nymph
#

yep, missing a }

ivory bobcat
#

For the class.

vocal fable
#

wdym

slender nymph
#

you have an opening curly brace for the class. where is the closing one?

vocal fable
slender nymph
#

that second one you have circled is the closing brace for your Update method

ivory bobcat
#

The one you circled is for Update according to indentations.

slender nymph
vocal fable
#

oh

#

damn

#

thanks

hoary citrus
#

If you had just trusted the error and added the curly brace you would have saved a lot of time 😂

toxic void
#
gameObject.transform.position = new Vector3(x, y, 0);

Why do I get an error from this?

slender nymph
#

you've probably got that inside of a static method

toxic void
#

Am I unable to referance gameObject inside a class?

chrome scarab
#
using UnityEngine;

public class EnemyHealth : MonoBehaviour
{
    public float enemyHealth;
    public SpriteAttack killedEnemies;

    // Start is called before the first frame update
    public void Start()
    {
        enemyHealth = SetBaseEnemyHealth();
    }

    // Update is called once per frame
    void Update()
    {

    }
    public float SetBaseEnemyHealth()
    {
        float health1 = 100;
        health1 += killedEnemies.killedEnemies;
        return health1;
    }

Hello, I wrote a code like this, but it gives the following error:

NullReferenceException: Object reference not set to an instance of an object
EnemyHealth.SetBaseEnemyHealth () (at Assets/Scripts/EnemyHealth.cs:22)
EnemyHealth.Start () (at Assets/Scripts/EnemyHealth.cs:11)

I'm sure I selected the sprite attack file in the inspector, and the killedenemies variable was initially set to 0 as follows:

public int killedEnemies = 0;
cosmic dagger
slender nymph
cosmic dagger
toxic void
cosmic dagger
chrome scarab
slender nymph
cosmic dagger
chrome scarab
slender nymph
cosmic dagger
# toxic void oh I see

when BodyPart is initialized, the calling script must pass a GameObject to its constructor . . .

chrome scarab
toxic void
slender nymph
chrome scarab
slender nymph
#

and still you are thinking about the wrong variable because you've decided to give the variable the same name as the one inside the SpriteAttack class.

chrome scarab
slender nymph
#

look directly to the left of what you have highlighted. that is what is null

chrome scarab
slender nymph
#

where do you assign anything to that variable

#

hint: you don't which is exactly what it is null

tame mesa
#

Hello, someone can explain me why my Tilemap is outlined by orange glow ?

slender nymph
#

you have gizmos enabled

#

it's just a gizmo showing the selection outline. it will not show in the actual game

chrome scarab
# slender nymph

Isn't it enough to assign in the inspector window? Do I need to create getComponent with void start?

slender nymph
#

assigning in the inspector is enough. provided you do that for every instance of that component

chrome scarab
#

I already did it.

tame mesa
slender nymph
toxic void
slender nymph
# chrome scarab I already did it.

not for every instance you didn't. otherwise it wouldn't be throwing a null reference exception. add this line to Start: Debug.Assert(killedEnemies != null, $"Oh look, the component was not assigned on {name}", gameObject);

cosmic dagger
chrome scarab
slender nymph
#

put it before the line that was already in Start

chrome scarab
slender nymph
#

you probably didn't assign the variable on your prefab and only assigned it on the one in the scene

chrome scarab
#

yep. it's isn't assigned to prefab

#

tysm @slender nymph

#

Why does the type mismatch occur when I select it?

slender nymph
#

prefabs cannot reference in scene objects. you need to pass the reference to it when you spawn it

toxic void
#

I have no idea why the instantiate isn't working, it just doesn't create anything when the game is running

tacit river
#
private void OnCollisionEnter2D(Collision2D collision)
    {
        placement.CanPlace = false;
    }
    private void OnCollisionStay2D(Collision2D collision)
    {
        placement.CanPlace = false;
    }
    private void OnCollisionExit2D(Collision2D collision)
    {
        placement.CanPlace = true;
    }```
the issue is there is a single frame when switching between 2 collisions that CanPlace becomes true and I need that to not happen
slender nymph
#

i would personally recommend use physics queries instead of relying on collision messages. you can use something like Physics2D.OverlapCircle (or whatever shape you need)

slender nymph
subtle hedge
#

ok so i runned into this little problem with the IK foot. So when i move the model up and down, the leg's target stay down on the ground, but when i move the cube forward the leg's target moves too and is dosen't stay on the ground to move the feet back. I know this i caused by the parenting of the target to the model, but how can i get past this issue without unparenting the targets from the model ?

#
public class IKMovement : MonoBehaviour
{
    public legTip[] legs;
    public float heightOffset;

    private void Update()
    {
        foreach (var leg in legs)
        {
            Ray legRay = new Ray(leg.tip.position + (Vector3.up * heightOffset), Vector3.down);
            if(Physics.Raycast(legRay, out RaycastHit hit, Mathf.Infinity))
            {
                leg.tip.position = hit.point;
            }
        }
    }
}

[System.Serializable] public class legTip
{
    public Transform tip;
}```
maiden minnow
#

Im using the old input system. How to check if the player is using keyboard or controller controls?

queen adder
#

is there an inverse of vector2.ToString()?

#

string.ToVector2() thingy something?

#

or do i have to write it

toxic void
slender nymph
#

then Instantiate is being called therefore the object is being spawned

wintry quarry
queen adder
#

yea figured i can just splitty thingies

slender nymph
#

what would you need to convert a string to a Vector2 for anyway? 🤔

queen adder
#
   public string FromToTarget( Vector2 main, Vector2 target) // used if there's a position in the string
    {
        string toret = "";
        float magni = (main - target).magnitude;
        if((int)magni == 0)
            toret = "0 C";
        else
            toret = $"{Mathf.RoundToInt(magni)} {lyx.func.CardinalDirectionWithTwoVector3(main, target)}";
        return toret;
    }
    
    void OnEnable()
    {
        string toDisplay = NoteString;
        toDisplay.Replace();
        noteText.text = 
    }````
#

btw, i wanna regex a string with any vector2 strings, how can i feed the matching results to FromToTarget then replace it that

#

is there a regex that outs something?

#

Regex.replace dont, does it?

toxic void
slender nymph
#

it is. it might be destroyed immediately but if that code is running and you don't see errors in your console then it is being spawned

toxic void
#

I don't see how the object is destroyed, nowhere in my game is there a line of code that destroys an object

slender nymph
#

well like i said, if that code is running and you don't see errors in your console then it is being spawned

#

add this line directly after it and show what it is printing: Debug.Log($"Instantiate has spawned a clone of {BodyPartPrefab.name} from {name}");
preferably screenshot the entire console window

queen adder
#

    public string FromToTarget( Vector2 main, Vector2 target) // used if there's a position in the string
    {
        string toret = "";
        float magni = (main - target).magnitude;
        if((int)magni == 0)
            toret = "0 C";
        else
            toret = $"{Mathf.RoundToInt(magni)} {lyx.func.CardinalDirectionWithTwoVector3(main, target)}";
        return toret;
    }

    Vector2 StringToVec(string ss) { return Vector2.zero; } 
    
    void OnEnable1()
    {
        string pattern = @"\(\d+[.\d\s]*,\d+[.\d\s]*\)";
        string input = NoteString;
        

        
        string result = Regex.Replace(input, pattern, FromToTarget(MainCharacterController.MainPosition, StringToVec( ""/* regex match */ )));
    }``` How can i make this work?
toxic void
#

in the game*

slender nymph
#

is this 2d?

toxic void
#

sorry too much using blender

toxic void
#

yeah

slender nymph
#

then either the objects are not being spawned within the camera bounds or they are behind the camera

toxic void
slender nymph
#

screenshot the inspector for it

toxic void
slender nymph
#

not the prefab, one of the objects actually in the scene

toxic void
#

idk why the position is 0 too thats weird

slender nymph
#

okay so it is at the same exact position as whatever its parent is. now keep in mind that child objects will also move when their parent moves

toxic void
#

ohhhhh

fading slate
#

Hi i just started today and i ran into a problem . The script i make for the ball doesnt work and it gives me no error

toxic void
#

How do I instantiate it without making it a child

#

I get it now

fading slate
#

it should look like this but mine doesnt

slender nymph
slender nymph
#

is your code exactly the same?

polar acorn
fading slate
#

oh wait wait let me take i step by step so

slender nymph
#

ah yeah, didn't even catch that

fading slate
#

i should name the script to Ball

#

?

slender nymph
#

that should be both the file name and the name of the class in the code, yeah

#

although now that i think about it, if you're on latest LTS that won't really matter

polar acorn
#

It doesn't matter what you call it as long as the file name matches the class name

fading slate
#

this is it by far
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
public Rigidbody2D rb2d;

private void Start()
{
    rbd2.velocity = Vector2.left;

}

}

slender nymph
#

yeah the class name is NewBehaviourScript. you'll want to change that to Ball

fading slate
#

so i should say public class Ball

slender nymph
#

yes. just like the tutorial you are follow does

fading slate
#

alright thanks a lot, i was a bit confused, this is really my first time having any encounter with coding

#

Assets\Scripts\Ball.cs(11,9): error CS0103: The name 'rbd2' does not exist in the current context
i got this now 😭

slender nymph
#

yep, you had that before too 😉

fading slate
#

and it still looks like this

north kiln
#

If your !ide is not underlining errors and giving you autocomplete you need to configure it

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

fading slate
#

I searched the issue on google but i can't seem to find an answer to why i dont have the game development for unity worload

slender nymph
#

just follow the instructions to install it?

#

assuming you are using visual studio and not vs code, that is

fading slate
toxic void
#
void MoveSnake()
    {
        if (!(snakeDirection == Vector2.up && snakeY == 4) && !(snakeDirection == Vector2.down && snakeY == -4) && !(snakeDirection == Vector2.right && snakeX == 8) && !(snakeDirection == Vector2.left && snakeX == -8))
        {
            prevFrameSnakePosition = gameObject.transform.position;
            gameObject.transform.position += new Vector3(snakeDirection.x, snakeDirection.y, 0);
        }
        previousSnakeDirection = snakeDirection;
        snakeX = (gameObject.transform.position.x < 0)? gameObject.transform.position.x + 0.5 : gameObject.transform.position.x -0.5;
        snakeY = (gameObject.transform.position.y < 0) ? gameObject.transform.position.y + 0.5 : gameObject.transform.position.y - 0.5;


        GameObject bodyPart = Instantiate(BodyPartPrefab, prevFrameSnakePosition, new Quaternion(0,0,0,0));
    }

How can I save the bodypart variable at the end so that I can access it after the method finishes to do an operation on one of it's public variables every time this method runs? I thought of using arrays but that complicates stuff and means I need a 180 elements long array of gameobjects...

#

And I want to keep this simple as this is a game of snake

slender nymph
#

new Quaternion(0,0,0,0) is not a valid quaternion. use Quaternion.identity instead

slender nymph
#

that doesn't make it correct

uncut dune
toxic void
#

wdym

uncut dune
#

whats this

ivory bobcat
slender nymph
# toxic void wdym

i mean new Quaternion(0,0,0,0) is not a valid quaternion. use Quaternion.identity instead

toxic void
#

Yeah I did it can you please help me with the question

uncut dune
polar acorn
slender nymph
toxic void
polar acorn
toxic void
#

alr, it didnt actually make any difference though

ivory bobcat
# uncut dune but what does it mean, cant I modify a dic?

You cannot modify a collection when you're traversing through it with foreach. Foreach promises that every element will be visited (unless you do an early escape) thus you'll get an error as you're violating the promise (probably more complicated stuff under the hood but that's the gist of it).

toxic void
#

so I dont really get what was the point of doing that

uncut dune
#

creating an exception

#

and iterating thru all objects of a dic

#

I mean all keys

ivory bobcat
#

Maybe post more of what you're trying to do. Likely you need to take a different approach to this.

uncut dune
#

this is the loop

ivory bobcat
#

Lots of folks are here. I'm on mobile and just doing what I can. Other dudes here are outstanding though.

#

How to post !code btw

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

uncut dune
#
foreach(GameObject enemies in enemiesToBeSpawned.Keys)
                    {
                        currentNumberOfEnemiesToSpawn = allRooms[CurrentRoomType].NumberOfEnemiesAtATime;
                        if(currentNumberOfEnemiesToSpawn > 0)
                        {
                            int number = enemiesToBeSpawned[enemies];
                            while(number > 0)
                            {
                                GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
                                ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
                                colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
                                colliderStats.enemy = enemies;
                                number -= 1;
                                currentNumberOfEnemiesToSpawn -= 1;
                            }
                            if(number == 0)
                            {
                                enemiesToBeSpawned.Remove(enemies);
                            }

                        }

                    }

ivory bobcat
# uncut dune

The quick and dirty solution would be to copy the keys collection and iterate it

#

Allowing you to modify the actual dictionary

uncut dune
#

yah that would work if I put them in a list

#

since they would be the same keys as the objects of the list

ivory bobcat
#

var copy = new List<...>(keys);

signal coral
#

What's the reason for this code?

 if(number == 0)
                            {
                                enemiesToBeSpawned.Remove(enemies);
                            }
slender nymph
#

yeah that's what is causing the error

ivory bobcat
#

Reminder, it's the dirty solution so if performance is a factor you may want to consider a different approach

uncut dune
#

why keep the key

slender nymph
#

and it seems like they just remove the object when done spawning them and are doing it for every key in the dictionary. so why not just clear the dictionary after the foreach loop?

signal coral
#

So it's a Dictionary<GameObject, int> ?

uncut dune
thorn vessel
#

how do I see my particle system? Like turn it on when colliding with something?

uncut dune
#

so there arent so manny enemies

neon stirrup
#

Hi I have a idea and don’t know how to do it

slender nymph
thorn vessel
#

This error keep on popping up
"MissingComponentException: There is no 'ParticleSystem' attached to the "Bird" game object, but a script is trying to access it.
You probably need to add a ParticleSystem to the game object "Bird". Or your script needs to check if the component is attached before using it.
UnityEngine.ParticleSystem.Play () (at <b6edb49129684880865710f98e97a458>:0)
BirdScript.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/BirdScript.cs:55)

"

slender nymph
#

did you read the error?

thorn vessel
#

i did

slender nymph
#

and what conclusion did you come to?

thorn vessel
#

im missing something

uncut dune
slender nymph
#

well it's certainly better than what you are trying to do now

uncut dune
uncut dune
slender nymph
# thorn vessel im missing something

yes, your "Bird" gameobject does not have a ParticleSystem on it, but a script is trying to access it. You probably need to add a ParticleSystem to the game object "Bird". Or your script needs to check if the component is attached before using it.

#

either that or you are calling GetComponent on the incorrect object 😉

thorn vessel
#

oh ok thanks 😄

signal coral
# uncut dune yes
foreach(var enemyToSpawnKeyValue in enemiesToBeSpawned)
{
    var enemy = enemyToSpawnKeyValue.Key;
    var count = enemyToSpawnKeyValue.Value;
    for(int i = 0; i<count;i++)
    {
      GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
                                ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
                                colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
                                colliderStats.enemy = enemy;
    }
}
//If I interpreted your code right you always just spawn all of them, so just clear the dictionary.
enemiesToBeSpawned.Clear();
#

Oh I missed this part

 currentNumberOfEnemiesToSpawn = allRooms[CurrentRoomType].NumberOfEnemiesAtATime;
                        if(currentNumberOfEnemiesToSpawn > 0)
                        {
uncut dune
#

well I dont always spawn all of them

signal coral
toxic void
#

Is there a way to remove an element from a list and make all indexes after it shift one place to the left so that it wont leave an empty index number?

fading slate
#

I have this exact same script as the tutorial i watch but i get the CS0103 The name 'rbd2' does not exist in the current context But the guy in the tutorial doesnt get it

uncut dune
keen dew
#

The guy in the tutorial didn't write "rbd2" like you did

queen adder
#

into the inspector

cosmic dagger
fading slate
#

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

public class Ball : MonoBehaviour
{
public Rigidbody2D rb2d;

private void Start()
{
    rbd2.velocity = Vector2.left;

}

}

#

This is my code

queen adder
#

or you can add rb2d=GetComponent<Rigidbody>() in the start

uncut dune
#

its rb2d

#

ur have an error

cosmic dagger
uncut dune
#

rb2d.velocity = Vector2.left; @fading slate change it to this

signal coral
# uncut dune yes pretty much

This is kind of messy, because dictionary doesn't have remove if. Should mostly work though.

var currentNumberOfEnemiesToSpawn = allRooms[CurrentRoomType].NumberOfEnemiesAtATime;
var toRemove = new List<GameObject>();
foreach(var enemyToSpawnKeyValue in enemiesToBeSpawned)
{
    var enemy = enemyToSpawnKeyValue.Key;
    var enemyCount = enemyToSpawnKeyValue.Value;
    var count = Mathf.Min(enemyCount, currentNumberOfEnemiesToSpawn);
    currentNumberOfEnemiesToSpawn -= count;
    var enemiesLeft = enemyCount-count;
    enemyToSpawnKeyValue[enemy] = enemiesLeft;
    if(enemiesLeft == 0) toRemove.Add(enemy);
    for(int i = 0; i<count;i++)
    {
      GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
                                ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
                                colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
                                colliderStats.enemy = enemy;
    }
}
foreach(var enemyToRemove in toRemove)
{
  enemiesToBeSpawned.Remove(enemyToRemove);
}
uncut dune
#

paste it there

cosmic dagger
fading slate
#

Oh yeah... I saw it sorry guyz

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

fading slate
uncut dune
fading slate
uncut dune
fading slate
#

now 0 errors good

cosmic dagger
queen adder
polar acorn
fading slate
queen adder
queen adder
fading slate
uncut dune
#

I remember when I started copying tutorials slowly and always having errors lmao

signal coral
# uncut dune thank you so much, I'll use this to guide myself into remaking it

The reason for this mess is that you can't edit a collection while iterating over it. If you used a list like this

public class EnemySpawnInfo
{
public GameObject Enemy;
public int countLeft;
}

And then a list like this List<EnemySpawnInfo> enemySpawnInfo;

You could just iterate over it backwards and remove elements as you go Like this.

for(int i = enemySpawnInfo.Count-1;i>=0;i--)
{
    var enemyInfo = enemySpawnInfo[i];
    var count = Mathf.Min(enemyInfo.Count, currentNumberOfEnemiesToSpawn);
    currentNumberOfEnemiesToSpawn -= count;
    enemyInfo.Count -= count;
    if(enemyInfo.Count == 0) enemySpawnInfo.RemoveAt(i);
    for(int o = 0; o<count;o++)
    {
      GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
                                ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
                                colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
                                colliderStats.enemy = enemyInfo.Enemy;
    }
}
uncut dune
#

some could say its a cannon event

signal coral
#

Which would simplify things

fading slate
#

I assign ball to Rb 2d and when i run it the ball simply dissapears and it shows none like i didnt drag it there

#

and now it randomly works

#

nvm

rigid wharf
#

I'm trying to change the color of a UI image from a button script, but I can't get a reference to it

#

"Image" isn't a class apparently

#

neither is button

uncut dune
#
Vector2 roomPos = rooms.RoomPos.position;
                List<GameObject> EnemiesToBeDeleted = new List<GameObject>();
                if(enemiesToBeSpawned.Count > 0)
                {
                    foreach(GameObject enemies in enemiesToBeSpawned.Keys)
                    {
                        currentNumberOfEnemiesToSpawn = allRooms[CurrentRoomType].NumberOfEnemiesAtATime;
                        if(currentNumberOfEnemiesToSpawn > 0)
                        {
                            int number = enemiesToBeSpawned[enemies];
                            while(number > 0)
                            {
                                GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
                                ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
                                colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
                                colliderStats.enemy = enemies;
                                number -= 1;
                                currentNumberOfEnemiesToSpawn -= 1;
                            }
                            if(number == 0)
                            {
                                EnemiesToBeDeleted.Add(enemies);
                            }

                        }
                    }
                    foreach(GameObject enemies in EnemiesToBeDeleted)
                    {
                        enemiesToBeSpawned.Remove(enemies);
                    }
#

@signal coral will this work?

#

I almost didnt have to change anything

#

instead of removing the enemies Im adding them into the list

#

and then after that foreach it starts deleting them

signal coral
#

there is one case where this code works kind of wrong:
if allRooms[CurrentRoomType].NumberOfEnemiesAtATime is for example 2
and int number = enemiesToBeSpawned[enemies]; is 4
it will spawn 4 enemies. Even though I think you want to spawn just 2

#

That's why I did:
var count = Mathf.Min(enemyInfo.Count, currentNumberOfEnemiesToSpawn);

signal coral
#

you only check if currentNumberOfEnemiesToSpawn is bigger than 0

uncut dune
#

would that cause any trouble?

signal coral
#

If it's bigger than zero, but smaller than " int number = enemiesToBeSpawned[enemies];" it will spawn more enemies than intended.

acoustic arch
signal coral
#

You should go through that code and try to understand the difference between the code I wrote and the code you wrote.

wintry quarry
polar acorn
uncut dune
#

what if my while statement

#

now is like this

signal coral
#

Yeah that's one way to do it

uncut dune
acoustic arch
signal coral
#

although there is one more problem if you do it like that. when you do "int number = enemiesToBeSpawned[enemies];" It makes a copy

wintry quarry
signal coral
#

at the end of your while loop you need to reassign it into the dictionary

#

like enemiesToBeSpawned[enemies] = number;

uncut dune
#

OHHH

#

so I should access it thru number

acoustic arch
uncut dune
#

should I call it directly?

acoustic arch
#

so it just doesnt grab the sprite for it

wintry quarry
signal coral
wintry quarry
#

and has an Image component. The rest is noise.

uncut dune
#

this way?

#

yup Im missing one

#

I'll change it now

signal coral
acoustic arch
uncut dune
#

but other then that is it okay?

wintry quarry
acoustic arch
wintry quarry
#

show what object you assigned to the InventoryCard variable

acoustic arch
#

like

signal coral
wintry quarry
#

Your code is trying to find a child object of this

#

iwth the name "cardImage"

acoustic arch
#

no it doesnt

wintry quarry
#

if no such child exists, that's why your code is failing

#

make sense?

acoustic arch
#

yeah

wintry quarry
#

so with that knowledge, you should be able to fix this, yes?

#

either changer the code

acoustic arch
#

so how do i change it so it looks for the image on that card tho?

wintry quarry
#

or change the object

acoustic arch
#

not in the child

#

i understand it

wintry quarry
#

is that not really simple?

acoustic arch
#

the tutorial im watching has a button with the icon inside it

#

while mine is just 1 image

#

not a child of a button