#💻┃code-beginner

1 messages · Page 384 of 1

quick pollen
#

at least it works

#

theres still some bugs tho

rich adder
quick pollen
#

sometimes it straight up takes 5 seconds to do the animation

#

idk why

#

it should be an instant transition

swift crag
#

sounds like you need to have a look at your animator controller

quick pollen
#

maybe it has to do with

#

oh yeah I know

#

I only make a transition from idle

swift crag
#

notably, if something has an exit time, then the transition can only happen at the exit time

quick pollen
#

doesnt have exit time

#

altho this is actually perfect

swift crag
#

if your idle animation is, say, 5 seconds long, and you have a transition with an Exit Time, it can take up to 5 seconds to hit the exit time

#

if there is no exit time, then the tranisition will happen immediately

quick pollen
#

I could force the player to stand still in order to cast the ability, which was my goal

swift crag
#

so if it isn't the animator controller, it's your code's fault

#

of course, you could be getting stuck in another state that doesn't transition back to Idle for a while

fair temple
#

my raycast cant detect my prefabs

        private void HandleInteractions()
        {
            Vector2 inputOfVector = new Vector2(0, 0);
            Vector3 moveDir = new Vector3(inputOfVector.x, 0f, inputOfVector.y);

            float interactDistance = 2F;
            
            if ( Physics.Raycast(transform.position, moveDir, out RaycastHit raycastHit ,interactDistance) )
            {
                Debug.Log(" - " + raycastHit.transform);
            }
            else
            {
                Debug.Log("No Hits");
            }
        }
quick pollen
fair temple
quick pollen
#

altho the way I did it is pretty cool like this

#

you can basically queue abilities

rich adder
# fair temple

is there a question here?
oh nvm just scrolled up 👍

quick pollen
#

and it plays when you stop moving

fair temple
#

look upper

quick pollen
#

altho im probably just gonna use an any state

rich adder
#

if at all

fair temple
rich adder
#

oh yeah Input vector is zero

#

what gives

fair temple
#

it gives me this thing

quick pollen
#

@swift crag using any state is better tho I suppose
now I just need to figure out a good way to stop all motion

rich adder
swift crag
# fair temple

you are explicitly making a [0,0,0] vector in your code

rich adder
#

also you are meant to debug the collider.name

swift crag
#

of course the raycast does not go anywhere

quick pollen
#

ty tho

fair temple
swift crag
#

not do that

summer stump
rich adder
#

don't assign zero?

swift crag
#

presumably you want to use your movement direction from somewhere else in your code

rich adder
#

why call it inputOfVector if you are not capturing any inputs with it..

quick pollen
#

instead of multiplying the player's speed by 0 I just straight up turn off the script that handles all that stuff lol
this will cause problems later

quick pollen
#

that script also handles things like

#

gravity

#

camera changes

rich adder
#

thats a big script

quick pollen
#

but tbf the ability does make you float, so having gravity turned off kinda makes sense

rich adder
#

maybe do just set move vel to 0

quick pollen
#

its actually not

#

the entire thing is like 120 lines

#

I can probably have a different script just for camera changin tho

#

just so it doesn't turn off camera switching

rich adder
#

i would not even dare to add a camera switching method or system inside a player move script :

#

maybe couple of years ago lol

#

It only makes sense a camera switching functionality has its own script..

quick pollen
#

yeahhh

#

I mean

#

I put it there because I had something with moving faster in one of them I think

#

i cant remember

rich adder
#

yah when you start having other scripts handle other aspects of your objects that will it gets a bloody mess

#

I had helped someone fix their project they were literally modifying Timescale in like 4 different places wondering how which one now causing unwanted behaviors

#

if you had a single script only handle timescaling , there is no second guessing

ember tangle
#

should a state machine be made using abstract classes or interfaces?

rich adder
#

or start simple and use an enum

ember tangle
#

I have it with abstract classes but since no function is actually implemented in the abstract base class I feel that it would be just as good using Interfaces... Googling is inconclusive.

swift crag
#

A base class for the states makes sense.

#

Notably, you might want to add some common functionality, like...

#
public virtual bool CanEnterState(State previousState)
{
  return previousState == null || previousState.priority < this.priority;
}
#

e.g.

ember tangle
swift crag
#

You can use it anywhere! It’s just an operator

ember tangle
#

hmm I don't know if I understand how that line works. What triggers the 'or' operator?

golden blade
#

Question, can I have multiple scenes running at once and use cameras and render textures to disply each scene onto one partitioned canvas?

#

Idk how to explain it

rich adder
eternal needle
ember tangle
#

oh its like shorthand right?

#

i think I understand

eternal needle
#

No it's not shorthand, it just is. These are boolean expressions, the method returns a bool

polar acorn
rich adder
swift crag
#
1 + 3
3 << 6
true || false
4 / 5f
#

nothing "triggers" the operators

naive pawn
#

(not to be confused with "bitwise" operators, which operate on the binary representation of integers)

swift crag
#

many of which are also binary!

#

as opposed to unary

-1
+3
!false
~5

or ternary

foo ? bar : baz
naive pawn
#

most operators are binary, notable exceptions are unary plus, minus, increment, decrement, logical not, bitwise not (unary) and conditional (ternary)

swift crag
#

the conditional operator is the only ternary operator I've ever seen, so it often gets called "ternary", yeah

naive pawn
#

(ts has a quaternary operator, that's fun to think about)

swift crag
#

it does? i've never heard of that

naive pawn
#

A extends B ? C : D for types, the extends is part of the syntax, there's no other conditions you can use

swift crag
#

ahh, I see

timber tide
#

I like the readability of binary/unary

#

if I want to try to compact my code as much as possible I'd just use python

naive pawn
#

pretty much all "normal" languages have them though?

swift crag
#

I use the conditional operator when I am just picking between two literals

#
val = Mathf.MoveTowards(val, activated ? 1 : 0, Time.deltaTime);
short hazel
#

Pretty sure that's still a ternary, where the condition is itself a binary. Like this (a extends B) ? 1 : 2

#

C# equivalent would be a is B

swift crag
#

Not if it's part of the syntax

#

i.e. if you can't write anything other than A extends B ? C : D

#

if you can write A ? B : C in the same context, or A extends B extends QWERTY ? C : D, or something, then the operator isn't quaternary

#

I mean, I guess you could say that it's a ternary operator with a very very restrictive first part

#

But then you could also argue that A ? B : C is actually a binary operator with a very restrictive grammar for its right hand side

naive pawn
#

astexplorer shows that A extends B ? C : D is a single construct with typescript or @typescript-eslint parsers

rich adder
#

unity moment..

naive pawn
swift crag
#

Typescript has a pretty wild type system

short hazel
naive pawn
#

yeah, that's for values

#

that exists in js

#

A extends B ? C : D is ts-specific, for conditional types

naive pawn
#

ts doesn't really mingle types and values
there's just v as T/<T>v for casting, and typeof v to get its type (and typeof v can either be a value or a type depending on context)

swift crag
rich adder
naive pawn
swift crag
#

I love a ewent Ôn d esh R ndere

rich adder
#

luckily restart fixed it. Strange

rich adder
#

recently

naive pawn
#

are you getting warnings about codecs

rich adder
#

if any were there they are gone now lol

naive pawn
#

ever tried to read warnings when 70% of the text is gone lol

#

(kidding, the text disappeared later)

rich adder
#

I forget I have Clear on Compile on and sometimes that fucks me over, especially fixing a bunch of errors now I need to reload the errors xD

naive pawn
#

also i noticed that it's not random parts of the string, it's random characters that disappear throughout, like the font for that character got nuked

thorn iron
misty pecan
#

i have an object following the mouse, and i want it to do something when it touches another object, which has a "is trigger" collider on it, why does this not work?

#

private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("touchpath");
}

rich adder
#

BinaryFormatter bf = new BinaryFormatter ();
FileStream fs = new FileStream (path, FileMode.Create);
😬

rich adder
misty pecan
rich adder
#

well then there you go

#

how do expect a physics event to be called without a physics object present

timid bridge
rich adder
#

you might not even need the rigidbody, just a use a overlap

eternal needle
misty pecan
#

do i turn simulated off on the rigidbody? i dont want any physics on either of the objects

rich adder
#

and unchecking simulated makes physics not work..

misty pecan
#

if i uncheck simulated, can i still use OnTriggerEnter2D

rich adder
#

I just said it makes physics not work

#

if its not "simulated" how do you expect it to call anything

misty pecan
#

ah ok

rich adder
#

you can just use an overlap

#

you don't even need rigidbody

#

or use box. whatever

misty pecan
#

thanks it worked once i added a rigidbody

#

ill just stick with this i think its alot simpler to me atleast

rich adder
#

gotcha, it just may not be as precise if you move transfoms directly

misty pecan
#

ahh

rich adder
misty pecan
#

radius.GetComponent<SpriteRenderer>().color = (255,0,0, 60);
how to set the colour to an rgba?

misty pecan
#

how do i assign it a new colour?

slender nymph
#

also Color uses float values from 0 to 1 not 0 to 255. however if you want to use 0 to 255 you can use Color32 which has an implicit cast to Color

rich adder
#

if you want to manually type the values make a new object of type Color32
or you can make it a field and change it in the inspector

misty pecan
#

it tells me i cannot implicitly convert type (float,float,float,float) to unityengine.color

#

Color red = (1f, 0f, 0f, .5f);
radius.GetComponent<SpriteRenderer>().color = red;

rich adder
#

because you're doing a tuple right now

misty pecan
#

is this what you meant?

languid spire
slender nymph
#

please go through the beginner c# courses pinned in this channel to learn how to do basic stuff like create an instance of an object

final kestrel
#

Hey All I am trying to add InventoryItems to my List once I spawn them. It works fine when spawning. When I despawn them on my UseItem and DropItem methods it kind of works for the first time when I empty my inventory. Removes them from the list. Then when I add more items and try to remove them from the list again. I get InvalidOperationException: Sequence contains more than one matching element it says.
https://hatebin.com/rbqfviogkq --> DespawnItem

https://hatebin.com/elmjucipqm --> SpawnItem

misty pecan
final kestrel
#

sequence it mentions is on the line with the linq

slender nymph
rich adder
#

very true

misty pecan
#

aight ill do that then

slender nymph
#

but it does seem like you've added the item to the list more than one time based on the error message

final kestrel
#

I just passed in the itemInSlot as you said

#

it works but like.

final kestrel
slender nymph
#

well you need to figure out where you are even adding them more than once in the first place

final kestrel
#

I have the list in the inspector. I see them getting added and removed.

#

Well it works for sure

slender nymph
final kestrel
#

No

slender nymph
#

well then you have duplicate item ids

#

those are the only two explanations for the error you received

final kestrel
#

becauuuse! I know because I have buttons that spawn items in my hotbar.

#

If there is items then It simply just wont add

#

now I have to figure a way to serialize a list of gameobjects in json

slender nymph
#

you don't. serialize the item data not the gameobjects themselves

final kestrel
#

I wanted to do this because I couldnt figure a way to serialize the Scriptable objects now dis T-T

slender nymph
#

create a class or struct that contains only the information absolutely necessary for the item. serialize that. then when you load that data you can spawn some prefab or something and pass that data to the spawned object to initialize itself with that data

final kestrel
#

Yes this starts to make sense now that I am struggling for like 3 days now

#

I watched some video where dude keeps the items in a database and then like gets them from there and puts them back into their places. I was going to try that

#

This whole save thing is out of this world. I was trying to make my character move a month ago

timber tide
#

keep your items simple for now. Make it so you only need to serialize an ID and slot

final kestrel
#

Well I do not hold any information on slot. I only spawn InventoryItem prefab on the slots transform.

#

InventoryItem basically has Item item scriptable object

#

Just initalizes itself on the given item.

timber tide
#

you dont need to serialize the prefab, you can just make a prefab table such that an id maps to the prefab

final kestrel
#

Like a database you say?

timber tide
#

pretty much but I usually think of databases are some remote server lol

final kestrel
#

Ah. My only database now holds Item scriptable objects now

timber tide
#

you can just make them a singleton in the scene that you initialize as you start the game

final kestrel
#

I understand that I have to break the stuff down into the most primitive type to serialize

#

but since I am so beginner. I cannot connect the dots haha

timber tide
#

prefab is already an amalgamation of stuff put together, so if you stick to id-ing that prefab as is, then the only thing you need to serialize is that

final kestrel
#

using UnityEngine;
[CreateAssetMenu(fileName = "Scriptable Object",menuName = "SO/Item")]
public class Item : ScriptableObject
{
   [field: SerializeField] public SerializableGuid Id {get;set;} = SerializableGuid.NewGuid();
   public Sprite image;
   
   
}

#

This is my Item object

#

I am using this custom made Guid class I got from a repo

#
using System;
using Systems.Persistence;
using UnityEngine;
using UnityEngine.UI;


public class InventoryItem : MonoBehaviour
{
    [HideInInspector] public Item item;
    
    [field: SerializeField] public SerializableGuid Id { get; set; } = SerializableGuid.NewGuid    ();
    public Image image;

    public void InitializeItem(Item newItem )
    {
        item = newItem;
        this.Id = newItem.Id;
        image.sprite = newItem.image;
        
    }

}

and this the inventoryItem sits on my prefab

timber tide
#

Alright, seems like you have the idea here

austere gyro
#

How to make delay in while?

timber tide
#

all you need to do is serialize that SO id and call some custom initialize constructor when you load those SOs back in, but if you were to also place them back into a specific slot of an inventory then you may need a specific struct to store that info too

final kestrel
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class InventorySlot : MonoBehaviour
{
    public Image Image;

    public Color selectedColor, notSelectedColor;

    public void Select()
    {
        Image.color = selectedColor;
    }

    public void Deselect()
    {
        Image.color = notSelectedColor;
    }
    // Start is called before the first frame update
    void Start()
    {
        Deselect();
    }

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

this sits on just a image prefab

timber tide
#

I usually just have some script that goes through all my prefabs/SOs of a type and adds them to a list but then on start I add them to a dictionary

final kestrel
#

Wonder if its reliable

austere gyro
timber tide
#

I think there is a more Unity friendly Task method that was added recently

timber tide
#

but if you do want that frametime sync, usually you do want it to be comparing frametime each frame

timber tide
final kestrel
#

Ah I see. I do not know about using singletons and game managers yet 😄

#

Gotta learn those some day

timber tide
#

it's just static classes with extra steps

#

benefits is that it exists on your scene and they have mono capabilities. Also you can clean them up if you wanted to and create a whole new instance.

final kestrel
#

Well that makes sense.

#

People are like noo singletons are bad, noo static classes shouldnt be used that much and shit

#

Gets me confused everytime whether I should study them or not

timber tide
#

Any manager can usually be a singleton; GamePools, Audio Systems, Particle Systems

#

Also, you can pretty much have a single singleton (the game manager) that references these managers

swift crag
#

I prefer singletons to a completely static class because:

  • it's easier to "un-singleton" if you decide you need multiple instances later
  • you can make a MonoBehaviour into a singleton, meaning you can easily serialize references to other assets
#

I have some singletons that load themselves from Resources on game start

#

Super useful. It doesn't matter which scene I enter my game from in the editor.

final kestrel
#

oo I saw that Resources looad thing while messing with the Scriptable objects as well. Could not understand what it does though

swift crag
#

It allows you to grab a reference to an asset by name.

final kestrel
#

by the name I set or? Like the asset's name

swift crag
#

Anything in a Resources folder is always included in the build. Normally, assets are only included if they're referenced by something else that's in the build (e.g. scenes)

#

Yes, by name

#
using UnityEngine;

public abstract class SingletonPrefab<T> : MonoBehaviour where T : SingletonPrefab<T>
{
    private static T _instance;

    public static bool Safe => _instance != null;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = Instantiate(Resources.Load<T>("SingletonPrefab/" + typeof(T).Name));
            }

            return _instance;
        }
    }
}
timber tide
#

I usually have a general load scene in all my games where I do load my managers in and bind them to "DontDestroyOnLoad" but the resource idea does sound useful as it is a pain to develop with lol

swift crag
#

this is in my GameController class

#
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    static void OnLoad()
    {
        Instance.Initialize();
    }
final kestrel
#

Uhh lots to learn lots to learn

timber tide
#

I'd consider making yourself a GameManager singleton as it's even suggested by Unity itself

verbal dome
final kestrel
swift crag
#

This freezes the game.

#

You can await a delay in an async method, or use coroutines to delay running something

final kestrel
#

Is it possible to instantiate prefabs from inside a list?

swift crag
#

Sure.

#

a List<T> can give you a T

#

so a List<MyComponent> can you give you a MyComponent, and you can instantiate that

austere gyro
final kestrel
#

Ahh nice thanks

swift crag
#

Yes. Invoke runs a method once, after a delay.

#

If you want to run a method many times, you could use InvokeRepeating

#

I would just write a coroutine that does it

#
IEnumerator SpawnStuff() {
  while (true) {
    LaunchProjectile();
    yield return new WaitForSeconds(2f);
  }
}
#

for a few reasons -- consider how you could do this

#
IEnumerator SpawnStuff(float startInterval, float endInterval, float intervalStep) {
  float delay = startInterval;
  while (true) {
    LaunchProjectile();
    yield return new WaitForSeconds(delay);
    delay = Mathf.MoveTowards(startInterval, endInterval, intervalStep);
  }
}
#

This lets you spawn things once per startInterval, speeding up a little bit each time until you reach endInterval

austere gyro
swift crag
#

no, you use StartCoroutine(SpawnStuff()); to start running the coroutine.

#

You could do that in your component's Start method

austere gyro
swift crag
#

You need to add using System.Collections; to the top of your script

#

The full name of the type is System.Collections.IEnumerator

#

Your IDE should be able to suggest this.

austere gyro
austere gyro
indigo mirage
#

i'm new to unity and im trying to follow a tutorial on how to make a flappy bird (GMTK) but when it comes to having a trigger activate, I am not sure why but the trigger isnt even activating at all

queen adder
#

im following this tutorial but it doesnt give me the weapon options

indigo mirage
verbal dome
rich adder
#

thats probably Scriptable Objects

queen adder
#

so when he clicks create there is so section that says weapon like in the pick

verbal dome
#

I see Weapon as the first item in that menu

queen adder
#

thats a picture from the tutorail

verbal dome
#

How should we know that

rich adder
#

you either missed a step/video or it didn't compile code cause of error

verbal dome
#

Probably missing the CreateAssetMenu attribute

quick pollen
rich adder
zealous hatch
#

RoomInst = Instantiate(RoomPrefabs[RoomPicker], new Vector3(1, 1, 1));
how come the new vector3 is underlined red. Compiler Error CS1503

quick pollen
#

to be fair I probably could for like projectiles

rich adder
#

Scriptable Objects are insanely powerful in unity

quick pollen
#

but I usually just copy paste pre-existing projectiles anyway soooo

quick pollen
rich adder
#

ah yes

rich adder
#

anyway configure your IDE

#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

quick pollen
#

hah

rich adder
#

you lose track after a while

quick pollen
#

LOL the timing

quick pollen
weak grove
#

hello my loverlies, im interested in templates for visual stiudio for doing apps using xaml as an example, where do i get templates from or should i use another ide ?

queen adder
#

ok i was using visual code studio already @rich adder

tall torrent
#

how can I make a basic movement system for my character in a horror game i am making. I am also confused on how to make a camera movement system. Any help would be greatly appreciated. - thx in advance

weak grove
#

@verbal dome more c# related

verbal dome
eternal falconBOT
#

:teacher: Unity Learn ↗

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

verbal dome
#

!csharp

eternal falconBOT
weak grove
#

ah ty i didnt have one, 😄

rich adder
queen adder
#

also he has camera holder and i dont but i dont know how i would make that work

rich adder
#

You have clear syntax errors

rich adder
warm raptor
#

hello, so here is the code of the websocket serveur of my fps game. I want to make a void that is called like 20 time/s to send a message to each player to let them know the status of all the players of the game. But I can't make that void that is called 20/s in my class Lobby, I tried with a timer at the begining of the class Lobby, but it didn't work. Do you know how I can make this void ?

queen adder
#

i did this

#

do i do the debugging session

rich adder
queen adder
#

yeah ive done everything else

rich adder
#

did you read the full page

queen adder
#

but also in the package manager they are locked

rich adder
#

remove engineer package iirc

#

or click Unlock, you should be able to click Unlock on the page of package

queen adder
#

what happened

#

i click uninstall of engineering and now im on a weird page

rich adder
queen adder
#

its back

#

when i unlock them it doesnt give me uninstall options

#

remove i mean

rich adder
swift crag
#

you have to remove the engineering feature first

#

you have not removed the engineering feature

queen adder
#

oh its back im sure i removed it

#

ok yeah thats sorted

rich adder
#

you are on unity 2021 arent you

queen adder
#

im not sure i just installed it off the website a few days ago

rich adder
#

how are you not sure, it literally tells you in the application titlebar lol

queen adder
#

oh its 2022

rich adder
#

ohh ok . so is vscode highlighting error now?

#

you can click regen project files first maybe in Unity

queen adder
rich adder
#

click Show Error

#

see what it says, maybe you're missing .NET sdk somehow

queen adder
rich adder
#

yerp

#

make sure you download the SDK

queen adder
#

setup failed

swift crag
#

can you be slightly more specific

queen adder
#

i think this is the right one

rich adder
#

you def do not have an ARM cpu

#

you need x64

swift crag
rich adder
queen adder
#

yeah it failed too

#

im not sure

swift crag
#

and what is the error, then?

queen adder
#

the same

swift crag
#

screenshot it.

#

entire window

queen adder
swift crag
#

You ran the same installer again.

#

Pay attention.

queen adder
#

oh mb

rich adder
queen adder
#

ok its installed but it still saying i need a net sdk

swift crag
#

restart your computer

queen adder
#

👍

#

bruh what

#

im still getting the same errors

swift crag
#

yes

#

this will not magically fix your code

#

the point is to make your IDE start working correctly

#

you still have to actually fix your code

queen adder
#

no i mean the sdk ones

swift crag
#

screenshot your entire VSCode window

queen adder
rich adder
#

try regen project files in unity and open script again (open script from unity)

swift crag
#

Switch to the terminal

#

Then run this:

dotnet restore

#

Show me the result

queen adder
swift crag
#

i'm not sure you actually installed anything

queen adder
#

im sure i did

#

it said to give feedback after it was finished

swift crag
#

here, run this:

#

dotnet --info

#

show me the output -- most importantly, the "Host: " section that tells you which version of .net is being run

queen adder
swift crag
#

expand the terminal area so you can see more at once

queen adder
swift crag
#

it should produce something like this

#

that is an interesting thing to see

queen adder
swift crag
#

This is, once again, not what I'm asking for

#

If dotnet --info didn't produce a Host: section then please just say that

queen adder
#

ye i was just wondering if it had anything to do with it

rich adder
#

what about dotnet --list-sdks

queen adder
#

i think this is what you mean

rich adder
#

you have the runtime but not sdk it seems

swift crag
#

Oh I see what's going on here

#

So you have .NET 7.0.12 on your $PATH

swift crag
queen adder
#

ohh

swift crag
#

I haven't had to do this manually on Windows before so I'm unfamiliar with the process

rich adder
#

its not your fault, is windows being silly

swift crag
#

I just get the runtime from the .NET Install Tool extension

#

I guess the extension sees you have .NET installed already and isn't stepping in

#

(it's supposed to install .NET for you just for VSCode)

swift crag
swift crag
queen adder
#

👍

#

will i have to restart my pc again

swift crag
#

yeah

#

i need to go test this stuff out on my PC some more

queen adder
#

net 7.0 is out of support version do i still use it

swift crag
#

I'd just give it a try

#

I guess it'd make the most sense to remove .NET 7 entirely and install .NET 8

rich adder
balmy rivet
#

Can i ask for help with my program here?

rich adder
balmy rivet
#

yes

rich adder
balmy rivet
#

the player gets stuck

verbal dome
verbal dome
#

This approach is flawed anyway, as you noticed. If it goes into another object, you give it no chance to move away

verbal dome
#

I assume yes since you are already checking for collider overlaps

balmy rivet
#

yea i do, but won't i still have the same problem?

rich adder
#

you're already moving the velocity on rigidbody, you don't need anything else other than solid colliders

verbal dome
dense root
#

I am trying to use my button from a list of buttons, however when I try to actually call it to do something it throws an object reference null error
Button answerButton0 = this.answerButton[0].GetComponent<Button>();

The way it is declared at the header is as follows:
[SerializeField] private List<Text> answerButton;

Where did I go wrong?

dense root
#

Oh

#

Let me try that

verbal dome
#

Only answerButton here could throw a null reference exception

#

Or if you had a null item in the list

#

Maybe you have another instance of this component that is not properly set up?

swift crag
#

and if you need both the Text component and the Button component, you should create a new component that has fields for both

ivory bobcat
#

Assuming you've actually referenced it from the inspector, the collection cannot be null and the elements cannot be null - the component can though, as you're likely referencing it as something other than Button.

swift crag
#
public class AnswerButton : MonoBehaviour {
  public Text text;
  public Button button;
}

now you can reference the AnswerButton and then retrieve the Text and Button components from it

balmy rivet
#

@verbal dome with this? rigidbody.collisionDetectionMode = CollisionDetectionMode2D.Continuous;

verbal dome
#

But yes, you might also want continuous collision detection

balmy rivet
#

ok yea

verbal dome
#

Unrelated to the problem though

balmy rivet
#

is the best thing just box collider?

#

thats what i have

verbal dome
#

Depends on your game. Boxes might get stuck easier as they have corners

#

Circle or capsule are alternatives

balmy rivet
#

oh yea i found out

#

much better xD

#

only problem now is that the world starts rotating when i hit it from an angle

ashen ridge
#

Huh

queen adder
#

im still getting the same errors

swift crag
balmy rivet
#

no idea lmao, i got scared

#

its really just the player that rotates, but the camera is attached to the player so the world rotates aswell lmao

ashen ridge
#

Ok
Seems easy to fix, can you send a quick video

balmy rivet
swift crag
summer stump
queen adder
swift crag
#

and let me see the Host: section

queen adder
#

thats the whole thing

swift crag
#

scroll up

queen adder
#

i downloaded x64 should i try x86

swift crag
#

no, you should not

swift crag
# queen adder

this appearse to be the same version of .NET that you started with

#

what did you actually do to uninstall and reinstall it?

queen adder
#

i installed the cleanup and activated it

swift crag
#

switch to the Output tab and then switch to the C# option in the dropdown on the right side. I want to see which .NET it's actually using

dense root
#

Got it working, thank you so much all

swift crag
#

this is what I see, for example

queen adder
swift crag
queen adder
swift crag
#

this looks wrong

swift crag
queen adder
swift crag
#

the entire window, including the dropdown at the top

#

you are probably looking at the wrong output

queen adder
swift crag
#

that is not "C#"

#

that is "C# LSP Trace Logs"

#

pick C# and then share the entire output log

queen adder
#

oh mb

swift crag
#

The architecture of the .NET runtime (x86) does not match the architecture of the extension (x64).

hm, interesting

#

But looking at the rest of the log, that looks fine

swift crag
queen adder
swift crag
#

because the C# output looks fine

queen adder
#

i got this too

swift crag
#

but I see that the project failed to activate

queen adder
swift crag
#

hm, consider this:

#

close VSCode

#

go to the root of your project and delete the .csproj files

queen adder
#

the what

swift crag
#

as well as the .sln file

swift crag
queen adder
#

yeah

#

i mean where is it located

swift crag
#

there will be files in your project root (so, the folder that has your Assets folder in it) with .csproj extensions

#

it's the folder you created your unity project in

#

one will be named Assembly-CSharp.csproj, for reference

late burrow
#

and again that

swift crag
#

delete the .csproj files and the .sln file, which will be named after your project

late burrow
#

i made 2d array how i make it not null inside entries

swift crag
#

then, in unity, regenerate the project files from the External Tools window

queen adder
#

which bit

verbal dome
late burrow
#

everything inside array

#

also i meant array inside array not 2d array

swift crag
#

Assembly-CSharp and "My project (1).sln"

verbal dome
swift crag
#

i see that windows is hiding the file extensions

queen adder
#

do i restart unity

verbal dome
#

If the array has null entries then you haven't assigned anything to them

swift crag
#

Then you need to double click a script asset to open VSCode

queen adder
#

bro im getting the same things

swift crag
#

you appear to have something very weird going on, since i saw both 32-bit and 64-bit .NET installs from your screenshots

#

(x86 and x64, respectively)

queen adder
#

is it possible to skip this or is it neccessary

#

im meant to create asset menu

#

but if i cant fix this error im stuck out of the game

verbal dome
swift crag
#

i have no idea what's going on with your .NET install(s) though

#

you could also just try Visual Studio

#

i'm pretty sure it bundles its own .net runtime and SDK

queen adder
#

i think ill try it tommrow its getting late now

tall orbit
#

alguien habla español???

ancient seal
#

Where’s the best place to learn coding?

young lava
#

Hi! I feel like this is an easy solution, but I'm not actually seeing much online regarding my problem. So pretty much I am working on a projectile targeting system and I want to check if the projectile is actually landing in the current room the player is in. The issue I am running into is the logic for detecting a collider. My room pretty much has a roomCollider which is a tilemapCollider2D + compositeCollider2D, which encompasses the entire room. I've tried methods such as Physics2D.OverlapPointAll and OverlapPoint as well, but for some reason they are not detecting any colliders (even though the position is very clear inside the collider). Does anyone know what the issue is?

vale bronze
#

How do I stop my Rigidbody Controller from getting stuck on walls when moving? I've seen multiple sources online saying to add a physics material with 0 friction, however this doesn't do anything. If the player jumps, lands on the side of the wall, and keeps pressing forward, they just get stuck there and stop falling until they stop moving. Any ideas?

verbal dome
#

It should work for this usecase

verbal dome
#

I would make the velocity change weaker or nonexistent when you are on a steep wall

young lava
# verbal dome Show the code that you tried with OverlapPointAll
private bool IsPositionInsideTilemap(Vector3 position)
    {
        if (dungeonManager != null)
        {
            // Get the current room from dungeonManager
            GameObject currentRoom = dungeonManager.ReturnCurrentRoom();
            if (currentRoom != null)
            {
                Transform roomColliderTransform = FindChildRecursive(currentRoom.transform, "RoomCollider");
                if (roomColliderTransform != null)
                {
                    // Find the TilemapCollider2D within the current room
                    TilemapCollider2D tilemapCollider = roomColliderTransform.GetComponent<TilemapCollider2D>();
                    if (tilemapCollider != null)
                    {
                        // Ensure the position is on the same plane as the 2D physics
                        Vector2 point = new Vector2(position.x, position.y);

                        bool isInside = tilemapCollider.OverlapPoint(point);

                        Debug.Log("tilemapCollider.OverlapPoint(point): " + isInside);
                        Debug.Log("POSITION: " + point);
                        return isInside;
                    }
                    else
                    {
                        Debug.LogError("TilemapCollider2D not found in the current room.");
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                Debug.LogError("Current room is null.");
                return false;
            }
        }
        else
        {
            Debug.LogError("DungeonManager is null.");
            return false;
        }
    }

The debug statements in the inner most if statement chain are printing false so I know it is from lack of detecting colliders.

#

I've also simplified it to just printing every collider hit in OverlapPointAll and no colliders are found

verbal dome
#

And might also wanna try asking tomorrow when most people arent sleeping

young lava
verbal dome
#

Btw, there also seems to be Collider2D.OverlapPoint if you want to check if the point is on a specific collider

swift crag
#

that's being used here

#

I don't see OverlapPointAll anywhere, though, which is confusing me a bit

young lava
#

Oh I can send you my overlap point all version

swift crag
#

The debug statements in the inner most if statement chain are printing false so I know it is from lack of detecting colliders.

So it's not logging TilemapCollider2D not found in the current room, correct?

young lava
#

correct

verbal dome
#

They said Physics2D.OverlapPoint in the first question so I just assumed

swift crag
#

Make sure you don't have multiple tilemap colliders (one of which would presumably be completely empty)

#

you should also check if your tilemap collider actually has any solid spaces

young lava
#

I do have multiple tilemap colliders but in the if statement chain I loop through very specific gameObjects to make sure I get the correct one located on the right gameObject. By solid space do you mean like physics space or if the collider is present, because the collider is there.

Also here is my other snippet of code, I just put this on an empty gameobject over my room collider and it is not printing anything.

https://pastecode.io/s/tsicew49

swift crag
#

as in, is the tile collider actually solid anywhere?

#

are there any solid tiles?

young lava
#

Yes there are solid tiles, though I do have the tilemap renderer turned off but if I turn the renderer back on, then a bunch of tiles appear.

swift crag
#

the code should find that collider

young lava
#

yep I added a 2d box collider to to same spot the testing script is located on and it prints it using OverlapPointAll

#

So it seems like it is just something wonky with the tilemap collider/composite collider right?

swift crag
#

can you prove that the tilemap collider is actually solid at that point?

#

like, by bumping into it with the player?

#

Tiles have to have a physics shape configured for them

young lava
#

Oh sorry, I might have misunderstood by solid, do you mean physically interact? The collider is an isTrigger, the player can't actually physically interact with the collider, it's pretty much used to check if the player is in the room or not for other scripts.

swift crag
#

Oh, if it's a trigger collider, then you have to make sure that you've turned on "Queries Hit Triggers" for OverlapPointAll to detect anything

#

I'd still expect the OverlapPoint method to have worked

young lava
#

Ya I just turned on isTrigger for the test collider we added and it works fine too xD confusion

swift crag
#

I'm currently doubting that your tilemap collider is actually covering any space at all right now

young lava
#

Okay, I'll try that. Does overlapPointAll require collisions between the two layers of the script and the collider to be turned on? I searched that up and sources say that doesn't matter.

swift crag
#

OverlapPointAll doesn't care about the layer your component happens to be on

young lava
#

Okay so I turn off is trigger and enabled collisions between playerPhysics and the collider layer and yes the player is running into the collider and interacting with it.

swift crag
#

Now, disable the tilemap collider

#

Do the collisions stop?

young lava
#

yes

swift crag
#

Very odd.

#

here's one thing: try logging the bounds property of the tilemap collider

#

see what space it covers

#

I would also make sure you're getting the correct collider by doing this:

#
Debug.Log("Using this collider.", collider);
#

clicking on that log message will take you to the object referenced by collider

young lava
#

Okay I positive it is a composite collider issue

#

I just turned the test collider into a box + composite collider and it is no longer detecting

swift crag
#

ah, i completely glossed over that

#

Did you set the composite collider to 'outlines' mode?

#

if so, it doesn't have an interior -- it's strictly an edge collider

young lava
#

ah yes.

#

thank you

#

very much

#

this has been annoying XD

swift crag
#

no prob :p

timid hinge
#

i dont know what can i do to solve it

#

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

public class elementalStaffSpawner : WeaponSpawner
{
protected override IEnumerator StartAttack()
{
EnemySpawner enemySpawner = EnemySpawner.GetInstance();

    while (true)
    {
        UpdateAttackPower();
        UpdateAttackSpeed();

        if(enemySpawner.GetListCount() > 0)
            SpawnWeapon(Direction.Right);

        yield return new WaitForSeconds(0.1f);

        if (GetLevel() >= 2 && enemySpawner.GetListCount() > 0)
            SpawnWeapon(Direction.Right);

        yield return new WaitForSeconds(0.1f);

        if (GetLevel() >= 3 && enemySpawner.GetListCount() > 0)
            SpawnWeapon(Direction.Right);

        yield return new WaitForSeconds(0.1f);

        if (GetLevel() >= 5 && enemySpawner.GetListCount() > 0)
            SpawnWeapon(Direction.Right);

        yield return new WaitForSeconds(0.1f);

        if (GetLevel() >= 7 && enemySpawner.GetListCount() > 0)
            SpawnWeapon(Direction.Right);

        yield return new WaitForSeconds(GetAttackSpeed());
    }
}

}

vale bronze
vale bronze
#

for the first error, it may be that you have two classes called elementalStaffSpawner. again, renaming one of the classes by renaming the file and the class name should fix it. I may be wrong about this error but I'm pretty sure it's this

timid hinge
#

thanks solved already

#

but this one

#

its on 114 line what can i do ?

vale bronze
#

All of those mean that the respective variable is null (doesn't exist).

eternal needle
#

That is some code

#

Null errors are always the same, there is a shitton that can be null there

timid hinge
vale bronze
#

so I guess the if statement part is returning null? I would need more code to understand. can you explain what the if statment is checking?

timid hinge
#

is it something on inspector or is in the code

vale bronze
#

I think it'd be in the code unless ItemAssets is something in the inspector

eternal needle
#

You need to debug and find that out for yourself. There are so many parts there that can be null

timid hinge
#

item assets its all good

rocky canyon
#

u got 2 errors about the object pooler and 1 about ur inventory..

#

in those scripts / functions use null checks b4 u run any code on stuff

#

but the real solution is to fix those in the first place.. if ur trying to use something make sure its assigned or referenced somehow

summer stump
violet glacier
#

What's the best way to pause certain objects/ui/animation while keeping some objects moving?

rich adder
summer stump
versed light
#

when is transform.hasChanged ever false i have a component where i never change the transform data yet hasChanged is always returning true in the update method. even when set to static its still returning true

north kiln
versed light
#

no ? wouldnt they set it to false on the next frame?

#

docs dont really say if they set it to false or not, does it just stay true until we set it to false?

versed light
#

ah wow

final plover
#

Not sure exactly what channel to post this in but im having a weird issue. As seen in the editor the ground is below the player. The player is also colliding with the ground. For some reason the ground is not showing in game. The player is on layer 2, the ground is layer 3. The camera should be showing it and if you go to any ground instantiations that are closer to x=0 then they are visible. I cant quite find where it cuts off.

spare mountain
final plover
#

Its at z=0

spare mountain
final plover
#

about 3

slender nymph
#

your ground is behind the camera

spare mountain
#

@final plover ^^

final plover
#

ah thx

slender nymph
#

you typically want to stick your camera at -10 so that doesn't happen

jaunty bone
#

y'all

#

im lowkey understanding it

#

like ngl this coding shit kinda easy

#

(prob gonna regret that alter on)

lethal smelt
#

is this gd script?

jaunty bone
#

walalhi

#

no

#

its c#

spare mountain
willow scroll
spare mountain
#

not unity tho linux

willow scroll
spare mountain
willow scroll
spare mountain
lethal smelt
elder osprey
#

I have a script that makes objects float at an offset in front of the player. I am using a lerp to make the object position smoothly, but I'm experiencing an issue where the objects lag behind and stutter frequently on lower end PC's. Here is my script: https://hastebin.com/share/owepohimix.csharp. Video recorded on M1 Macbook Air: https://streamable.com/3ibrw8

Watch "2024-06-16_01-58-30" on Streamable.

▶ Play video
eternal needle
elder osprey
eternal needle
elder osprey
stiff briar
#

guys
what is deltatime
cant find it on wiki

elder osprey
# stiff briar guys what is deltatime cant find it on wiki

DeltaTime. This video is all about that mysterious variable that oh so many game developers seem to struggle with. How to use DeltaTime correclty? I got the answers and hope this video will help to deepen your understanding about how to make frame rate independent video games.

0:00 - Intro
0:34 - Creating The Illusion of Motion
1:11 - Simple Li...

▶ Play video
faint sluice
#

Also this video above ^

eternal needle
void thicket
void thicket
#

In this case it's time difference between current and previous frame

stiff briar
#

i thought its second and frame

void thicket
#

It's unit is in seconds for Unity

#

But it's not tied to concept of dt

stiff briar
#

btw imma ask a basic question maybe someone who got enough time will answer it
if i were to make a running mechanic in a 3d game
can i use like... public class walkspeed... and public class runspeed...
then use something like, if (shift get pressed) then walkspeed == runspeed?
(i cant open unity right now so i cant experiment)

elder osprey
faint sluice
elder osprey
ruby python
#

Mornin' all,

In my projects I like to generate levels randomly (cause I suck at actual level design. lol.) and I've always used the same/similar method.

Basically I just instantiate a bunch of objects in each Method one after the other, if this was a continuous thing the performance would tank, but as it only happens on level start I figured there wouldn't be a performance hit.

https://hastebin.com/share/nozoferegu.csharp

This is my current level generation, it's pretty simple at the moment, but I will be adding more 'layers' (ground rocks, bushes, trees etc. to fill out the level), but I was wondering if there was a better/more efficient way to do it?

stiff briar
#

ahh so it could work then? aight imma find the working script for it

faint sluice
#

And move my object using currentspeed

eternal needle
stiff briar
stiff briar
#

ok thx

faint sluice
ruby python
faint sluice
faint sluice
elder osprey
ruby python
# faint sluice Also object pooling is never about "removing" items , I'm concerned

Huh? not sure what you mean by this. Why concerned? What I mean by removing is that the map items never get removed after they've spawned at the level start, so there's no need to pool them (instantiating directly, or instantiating them into a pool is the same thing). A pool just lets you activate/deactivate the object(s) instead of destroying and instantiating over and over.

charred condor
#

Is there a way or some type of algorithm or way to center the player in the camera's viewport by only moving the camera on the global X & Z axis (without changing the camera's rotation or height)?

charred condor
#

Thanks @rich adder

abstract finch
#

Is something like this possible? An abstract class thats able to do a coroutine?

faint sluice
#

Say you need 500 trees to be randomly spawned in the game, premake the pool of 500 trees and spawn them at runtime

rich adder
#

how can you override

ruby python
faint sluice
abstract finch
#

Sorry I'm not sure what it means, so I need to make the handlestate coroutine public virtual override?

faint sluice
abstract finch
faint sluice
abstract finch
#

yea I got it now

faint sluice
#

Virtual only needs to be added in parent class, but it already has abstract so it's no longer necessary

abstract finch
#

Got it thanks

rich adder
#

yes abstract becomes similiar to Interface

abstract finch
#

I've only worked with interfaces in place of these before but i figure this is a better approach for serialization

tepid steeple
#

Guys i have a problem i finally completed project but not work online in apk. When i test the project in pc its works done and easily auto-find server and connect. In mobile cant find the host server how can i fix this ?

rich adder
#

you can only inherit one, but you can implement many interfaces

abstract finch
#

thats true actually

rich adder
abstract finch
#

what i struggle with when doing interfaces is serialization, lets say that i have IAction and IState. IAction also has IState. IAction like Attack1
In order to identify them at start I have to do GetComponentsInChildren<IState>, with this I can just drag it to the inspector

#

but yeah it's something I should think about later

rich adder
#

I guess, otherwise normally they would Register themselves

#

my save sytsem, if I have object that implements ISaveable, I'm not gonna go look for that every time or maybe you might miss spawned ones.
The ISaveable takes care of registering itself to the main Saving Script that needs ISaveables to store

charred condor
# rich adder cinemachine
void SmoothCenterOnPlayer()
    {
        if (isLockedOnPlayer)
        {
            centerTimer += Time.deltaTime;
            float t = centerTimer / centerDuration;

            // Get the ray from the camera to the center of the viewport
            Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
            Plane groundPlane = new Plane(Vector3.up, Vector3.zero);

            if (groundPlane.Raycast(ray, out float enter))
            {
                // Get the world position of the viewport center
                Vector3 currentViewportCenter = ray.GetPoint(enter);

                // Calculate the target position to move the camera
                Vector3 targetPosition = transform.position + (playerTransform.position - currentViewportCenter);

                // Lerp the camera's position to smoothly move it
                transform.position = Vector3.Lerp(transform.position, new Vector3(targetPosition.x, transform.position.y, targetPosition.z), t);
            }
        }
    }

Found a solution online to do it programmatically. But still going to check out cinemachine.

eternal needle
faint sluice
charred spoke
#

The scene needs to instantiate them when it loads as well

faint sluice
#

Hmmm tru nvm then

eternal needle
eternal needle
#

it would just be moving the lag from one area to another

faint sluice
eternal needle
#

thats somewhat unrelated, because thatd imply the prefabs were in the scene manually placed. A pool still could place objects in DDOL

#

the only use case i guess would be if they wanted to reuse objects between maps, not sure how much that'd really matter though

carmine narwhal
#

why does this happend ? first picture looks right but when i do a prefab from the origin cube the transform dissapears like this and now i cant add anything to the transform field

languid spire
#

transform field?
you have the prefab selected not the gameObject in the hierarchy

#

also not a code question

tepid steeple
#

@languid spire

#

whats up

#

Can you help me on networking ?

#

In PC host and client perfectly working but in mobile not find the server.

languid spire
tepid steeple
carmine narwhal
languid spire
ruby python
carmine narwhal
languid spire
eternal needle
ruby python
eternal needle
ruby python
#

And would be a big help based on what I'm planning on doing (different maps/levels set in different locations/time periods etc)

#

Just thinking out load. But I'm thinking Scriptable object of type 'Spawnable Object' add them all into an array ((SpawnableObject[])), then in my map generation do a foreach SpawnableObject and spawn that way?

eternal needle
#

in your case, you literally just need to add fields relevant to whats spawning, like GameObject for the prefab, an amount to spawn, then possibly values for how it should rotate or scale etc

ruby python
#

Yeah I'm using an SO for my enemy stats atm (speed/damage/health), really simple, but got it working, so I'm getting there. lol.)

eternal needle
#

id probably start with this, and add whatever else you know you need

public class SpawnableObjectSO : ScriptableObject
{
    public GameObject prefab;
    public float minSpawn; 
    public float maxSpawn; 
    public Vector3 maxDeltaScale; // if you want random scale
    public Quaternion maxDeltaRotation; // for random rotation
}
#

though you might need to add more like information of how it should spawn in relation to the ground, should it spawn inside (like a rock) or exactly ontop like a flower

ruby python
#

Yeah. All the things generally spawn the same (except obviously the two things I included in my example, they spawn in a circle lol.). But everything else is randomly placed/rotated/scaled, so yeah an SO make perfect sense with just one method to spawn them in based on the SO values.

waxen cypress
#

Anyone know how to fix this?

languid spire
waxen cypress
#

Alright thanks!

#

Saving will still work yeah?

languid spire
#

yes

waxen cypress
#

Alright Thanks.

ruby python
#

Okay, so I think I have my map generation sorted using an SO (I haven't made the items/SO objects yet, but in my head this should work fine, just looking for an extra set of eyes to see if I've understood it all correctly if that's okay. 🙂

SO Setup.

[CreateAssetMenu(menuName = "Ground Items/Ground Item")]
public class GroundItem : ScriptableObject
{
    public string groundItemName;
    public GameObject[] groundItemPrefabs;
    public Transform groundItemParent;
    public float groundItemCount;
    public float groundItemMaxRadius;
    public float groundItemMinScale;
    public float groundItemMaxScale;
}

Implementation

    [Header("Ground Items")]
    [SerializeField] GroundItem[] groundItemSOs;
    void SpawnGroundItems()
    {
        for (int gSO = 0; gSO < groundItemSOs.Length; gSO++)
        {
            for (int i = 0; i < groundItemSOs[i].groundItemPrefabs.Length; i++)
            {
                //Do ground item spawny things
                float randomRadius = Random.Range(0, groundItemSOs[i].groundItemMaxRadius);
                angle = Random.Range(0, 359);
                Vector3 pos = GameManager.Instance.HelperManager.RandomCircle(groundItemSOs[i].groundItemParent.position, randomRadius, angle);
                Quaternion rot = Quaternion.Euler(0, Random.Range(0,359), 0);
                GameObject newGroundObject = Instantiate(groundItemSOs[i].groundItemPrefabs[Random.Range(0, groundItemSOs[i].groundItemPrefabs.Length)], pos, rot);
                newGroundObject.name = groundItemSOs[i].groundItemName;
                newGroundObject.transform.parent = groundItemSOs[i].groundItemParent;

            }
        }
    }
languid spire
#

mistake here I believe

for (int i = 0; i < groundItemSOs[i].groundItemPrefabs.Length; i++)
ruby python
#

Ah yeah, the groundItemSOs[i] should be gSO (on all). oopsy. lol.

languid spire
#

I would do

for (int gSO = 0; gSO < groundItemSOs.Length; gSO++)
        {
            var array = groundItemSOs[gSo];
            for (int i = 0; i < array.groundItemPrefabs.Length; i++)
            {
                var item = array.groundItemPrefabs[i];

then use item thereafter. it makes the code much more readable

ruby python
#

Right I got you.

#

Thank you 🙂

queen adder
#

the point system doesn't work.

languid spire
short hazel
#

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

short hazel
#

Do that first, then come back, this is a required step to get help here

vagrant ledge
#

hello guys I have a pickup and drop system for guns in my fps game with works fine when the animator is disabled on the gun
But when the animator is enabled, the gun teleports to the world origin

#

here is the code

willow scroll
short hazel
#

Yep that's an animator issue

willow scroll
#

If you want your animation to work properly, you have to create an empty GameObject inside of your gun and put your animator on it

#

Note that everything associated with displaying the gun should be put on that object too

#

E.g. SpriteRenderer etc.

short hazel
#

You have keyframed the gun's position at some point. When the animation plays, the animator sets that position back, moving the gun itself elsewhere (here, to origin)

willow scroll
austere gyro
#

How to make it so that if an object touches another object with the same name, it divade?

willow scroll
eternal falconBOT
fossil drum
austere gyro
austere gyro
short hazel
#

You should also avoid doing logic on object names, it has its flaws (names change, especially when you copy objects). Prefer detecting a script with the "name" as a variable inside of it

fossil drum
fossil drum
#

🎉

fossil drum
austere gyro
vagrant ledge
#

how can I disable animator with script?

fossil drum
verbal dome
#

With the word "unity"

vagrant ledge
#

i am dumb

austere gyro
#

its right?

verbal dome
austere gyro
verbal dome
#

Mind showing more of the code instead of one line?

short hazel
#

The parameter is named collision, not other

#

Which should probably be renamed to collider, since that's what it really is

short hazel
#

Syntax error, 'word' expected after "its"

#

Yes that is valid. You can give it any name you want, like other variables

austere gyro
short hazel
#

In this specific example, other will contain the other collider this object interacted with

#

Though to actually detect collisions you might want to use OnCollisionEnter2D(Collision2D other) instead, with the proper collider setup on your game objects

queen adder
#

the point system doesn't work.

swift crag
#

you can't just say "it doesn't work"

#

if it did work you wouldn't be here

#

so we have learned nothing

#

what is going wrong? what have you tried doing?

next ravine
#
SliderBG.name = "Background";
SliderBG.AddComponent<SpriteRenderer>();
SpriteRenderer BGsprite = SliderBG.GetComponent<SpriteRenderer>();
BGsprite.enabled = true;
BGsprite.sprite = Resources.Load<Sprite>("D:\\SteamLibrary\\steamapps\\common\\Soundodger 2\\Mod\\MododgerPortRoot\\ModTest\\Assets\\UI\\BadSlider01.png");``` should this work to create an object with a sprite on the screen/
#

i have no clue what im doing here

short hazel
#

It starts off well, but you cannot use Resources.Load() to retrieve elements that are outside your project, and you're not using the correct path format

#

Also AddComponent() returns the component it created, so you can do

SpriteRenderer BGsprite = SliderBG.AddComponent<SpriteRenderer>();

and spare yourself a GetComponent call

#

(or scrap 90% of this code and use a prefab instead)

swift crag
#

Yes, you should absolutely just make this a prefab

#

unless you're unable to do that because you're trying to mod a game, of course

orchid trout
#

What are possible reasons why my class cannot see my other classes type/existence?

#

even when I try to resolve the redline, it just wants to generate that other class. But that other class already exists

#

I cant pass CombatTrackerCommandPanel in directly instead of EditorWindow because it can't see that either

#

my real xy problem here is how do I force it to see it

#

it can see the generated one, why cant it see my one?

#

and why do these two scripts not conflict and complete despite having identical name and no namespace?

#

what I am actually trying to do is make a generic draw method for editor scripting window stuff and I need to reference but isolate the gui draw stuff from the main build stuff

late burrow
#

how i get dictionary by index

swift crag
#

anything in an Editor folder is automatically put into the Assembly-CSharp-Editor assembly, which is not referenced by the Assembly-CSharp assembly

#

unless you override that behavior with assembly definitions

orchid trout
#

Oh so the fact that its editor code blocks it off 🤔

swift crag
#

Right.

orchid trout
#

I know it has to be in editor because its editor code and breaks the build, I didnt realize other code cannot then see any of that

swift crag
#

If other non-editor code could see the editor-only code, then it would depend on being able to use stuff from the UnityEditor namespace

scarlet tiger
#

the alternative is to use preprocessor directives with UNITY_EDITOR to block the code from being in the build

#

so you can remove the editor folder and wrap the whole class

swift crag
#

yeah -- if you want part of a class to still exist in the build, then that's the way to go

late burrow
#

also does dictionary even keeps order i inserted stuff in it

scarlet tiger
swift crag
#

oh, maybe I am wrong!

#

I was thinking of SortedDictionary

#

yep

polar acorn
willow scroll
late burrow
#

yeah no int fails to be passed to string dictionary

timid hinge
#

boys i dont know what is null here all prefabs are active

late burrow
#

double click error see the line

timid hinge
#

sends me to here

#

and here

#

what im i supposted to do

#

im having this error for 2 days and i cant solve it

summer stump
timid hinge
#

weapondata is a script where a keep all weapondata

#

how can i share the code do you have that site?

summer stump
eternal falconBOT
timid hinge
short hazel
#

Errors have stack traces, which are indications on where execution was exactly when the exception occurred:

ObjectPooling.CreateObject[T] (T type) (at Assets/Scripts/ObjectPooling.cs:114) /*
|              Method                |  |               Path              | Line
#

This should get you on track

#

ObjectPooling.cs line 114

timid hinge
#

yes here

#

but what am i supposted to do right now

short hazel
#

Find on that line what is null

timid hinge
#

that is the problem friend i can find it nothing is null in my game 🥲

short hazel
#

You get NullReferenceException when you attempt to access something (using the .) on a value that is null

summer stump
#

It would tell you very fast what is null

#

Otherwise, put down some debug.logs

timid hinge
short hazel
#

Underlined red is everything that could be, or could return null

#

Check each

summer stump
timid hinge
short hazel
#

In the code directly, by debugging

#

You'd want to break that line up into multiple to ease out the process, because it's pretty huge right now

timid hinge
#

in my weapondata code isnt nothing null right?

urban escarp
#

How to fix this?

short hazel
#

Attempting to do things on them when they're null would result in a NullReferenceException

summer stump
#

Learn how to debug, and debug

#

Not much we can say beyond that

short hazel
late burrow
#

ok so what kind of data storage will be best for finding entry of largest index smaller than x number

polar acorn
late burrow
#

not in order

late burrow
#

well they are increasing but there are numbers missing

polar acorn
# late burrow not in order

How often are you going to need to do this search, and approximately how many entries do you expect to have to search

late burrow
#

1000 and maybe 100k of searches

timid hinge
#

guys please who have a time to solve me that error it will be very good for my live cause this is a project that a need to make and i cant solve this error and yall saying its a eazy error

timid hinge
#

this is very important to me

summer stump
#

We are not at your computer...

timid hinge
spare mountain
#

💀

summer stump
short hazel
#

Learn how to debug, it's easy

summer stump
timid hinge
spare mountain
summer stump
#

Just add the debugs we said.

TRY

timid hinge
#

what debugs?

summer stump
#

Debug.Log on all the things that could be null

spare mountain
#

do these people live life with a blindfold on

late burrow
summer stump
#

That was suggested a while ago, and would be a good idea

They seem to be ignoring all suggestions though unfortunately

timid hinge
#

problem solved now i have onther one error

#

is it the same think?

short hazel
#

Yes

polar acorn
# late burrow 1000 and maybe 100k of searches

Not sure what you mean by the 1000 for "how often" but you've got 100,000 entries in the collection, which would make sparse arrays inviable, they'd just be too big.

I think your best bet is ordered dictionaries. Loop over the keys and compare them to your condition, and store the value if it is less than that. When you hit the first value greater than your condition, break the loop and the last thing you stored is the biggest key that isn't over your condition.

timid hinge
#

its on line 166

polar acorn
short hazel
#

Follow the same troubleshooting steps. Stack trace to locate the line of code, then check what's null and make it not null

summer stump
late burrow
summer stump
eternal falconBOT
#

mad No

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

polar acorn
# timid hinge its on line 166

Something on that line is null but you're trying to do stuff to it anyway.

That is a hella complex line, you should split it into multiple steps for your own sake so you can more easily find what's null

short hazel
verbal dome
#

Like 6 things on that line could be null

late burrow
#

i miss times when editor said exact character count from where error starts

summer stump
polar acorn
short hazel
verbal dome
summer stump
languid spire
# timid hinge oh sorry about that

Do you ever take any notice of anything anyone says?
I told you days ago not to use compound statements and even showed you how to break them down