#💻┃code-beginner
1 messages · Page 384 of 1
you will never NOT have bugs lmao
sometimes it straight up takes 5 seconds to do the animation
idk why
it should be an instant transition
sounds like you need to have a look at your animator controller
notably, if something has an exit time, then the transition can only happen at the exit time
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
I could force the player to stand still in order to cast the ability, which was my goal
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
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");
}
}
@swift crag
is there a question here?
oh nvm just scrolled up 👍
and it plays when you stop moving
altho im probably just gonna use an any state
this one
new Vector2(0, 0)?
oky
@swift crag using any state is better tho I suppose
now I just need to figure out a good way to stop all motion
well either way your moveDir is wrong
you are explicitly making a [0,0,0] vector in your code
also you are meant to debug the collider.name
of course the raycast does not go anywhere
ty tho
but what should i do
not do that
Make it not zero
don't assign zero?
presumably you want to use your movement direction from somewhere else in your code
why call it inputOfVector if you are not capturing any inputs with it..
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
live in the now amirite :?
for real lol
that script also handles things like
gravity
camera changes
thats a big script
but tbf the ability does make you float, so having gravity turned off kinda makes sense
maybe do just set move vel to 0
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
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..
yeahhh
I mean
I put it there because I had something with moving faster in one of them I think
i cant remember
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
should a state machine be made using abstract classes or interfaces?
or start simple and use an enum
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.
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.
I didnt know you could use the || in the return statement
You can use it anywhere! It’s just an operator
hmm I don't know if I understand how that line works. What triggers the 'or' operator?
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
if either one is true it returns true, otherwise it returns false
It's the exact same thing as using it in an if statement
No it's not shorthand, it just is. These are boolean expressions, the method returns a bool
What do you mean "triggers"? It is an operator, like + or * but for booleans
maybe they thought you need
if(true) return true
else
return false
any binary operator can be used with two expressions
1 + 3
3 << 6
true || false
4 / 5f
nothing "triggers" the operators
(not to be confused with "bitwise" operators, which operate on the binary representation of integers)
many of which are also binary!
as opposed to unary
-1
+3
!false
~5
or ternary
foo ? bar : baz
most operators are binary, notable exceptions are unary plus, minus, increment, decrement, logical not, bitwise not (unary) and conditional (ternary)
the conditional operator is the only ternary operator I've ever seen, so it often gets called "ternary", yeah
(ts has a quaternary operator, that's fun to think about)
it does? i've never heard of that
A extends B ? C : D for types, the extends is part of the syntax, there's no other conditions you can use
ahh, I see
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
pretty much all "normal" languages have them though?
I use the conditional operator when I am just picking between two literals
val = Mathf.MoveTowards(val, activated ? 1 : 0, Time.deltaTime);

What is this power
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
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
A extends B isn't a standalone clause, extends isn't its own syntax (at least, not in this way), and you can't use anything else as the condition for the "ternary"
astexplorer shows that A extends B ? C : D is a single construct with typescript or @typescript-eslint parsers
unity moment..
it's a type operator
Typescript has a pretty wild type system
So there's this expression that looks like a ternary but is not, then the regular ternary expr ? a : b
yeah, that's for values
that exists in js
A extends B ? C : D is ts-specific, for conditional types
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)
it's so random, never had this happen on my version
i got it to happen consistently trying to import an mp3
I love a ewent Ôn d esh R ndere
luckily restart fixed it. Strange
now that You mentioned it i did import mp3s into this project 🤔
recently
are you getting warnings about codecs
if any were there they are gone now lol
ever tried to read warnings when 70% of the text is gone lol
(kidding, the text disappeared later)
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
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
Hello, I wish to know if this save load system from the following github is still pertinent, and can save/load MonoBehaviour, ScriptableObject, which contains custom classes as field and property.
https://github.com/NicolasPCouts/Save-and-Load-System
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");
}
BinaryFormatter bf = new BinaryFormatter ();
FileStream fs = new FileStream (path, FileMode.Create);
😬
does either object have a rigidbody
neither do
well then there you go
how do expect a physics event to be called without a physics object present
At least one needs a rigidbody with kinematic/dynamic
you might not even need the rigidbody, just a use a overlap
If you wish to know then 
Although this is literally 4 scripts, you can make your own better one in like 10 minutes.
do i turn simulated off on the rigidbody? i dont want any physics on either of the objects
you don't need it on both
and unchecking simulated makes physics not work..
if i uncheck simulated, can i still use OnTriggerEnter2D
I just said it makes physics not work
if its not "simulated" how do you expect it to call anything
ah ok
you can just use an overlap
you don't even need rigidbody
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html
but using the NonAllocating version
or use box. whatever
thanks it worked once i added a rigidbody
ill just stick with this i think its alot simpler to me atleast
gotcha, it just may not be as precise if you move transfoms directly
ahh
This is using BinaryFormatter, that alone is a sign for you not to use such an outdated way to do binary file. Microsoft has advised against using this formatter, new way uses BinaryWriter
radius.GetComponent<SpriteRenderer>().color = (255,0,0, 60);
how to set the colour to an rgba?
you're asigning a tuple rn lol
how do i assign it a new colour?
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
well you need to pass an object of type Color32 or Color
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
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;
because you're doing a tuple right now
is this what you meant?
do you know how to create a new Vector3 ?
correct, you need to call the constructor for the type you want
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
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
nevermind i figured it out all i had to do was write new Color
sequence it mentions is on the line with the linq
which you would understand how and why you need to do that if you bothered learning the fundamentals of the c# language
very true
aight ill do that then
you do not need to use the SingleOrDefault method at all. you already have a reference to the object in the list, just pass it to the Remove method
but it does seem like you've added the item to the list more than one time based on the error message
Hmm. I do not have any way to prevent adding items more than once
well you need to figure out where you are even adding them more than once in the first place
I have the list in the inspector. I see them getting added and removed.
Well it works for sure
and do you see the items added more than one time?
No
well then you have duplicate item ids
those are the only two explanations for the error you received
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
you don't. serialize the item data not the gameobjects themselves
I wanted to do this because I couldnt figure a way to serialize the Scriptable objects now dis T-T
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
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
keep your items simple for now. Make it so you only need to serialize an ID and slot
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.
you dont need to serialize the prefab, you can just make a prefab table such that an id maps to the prefab
Like a database you say?
pretty much but I usually think of databases are some remote server lol
Ah. My only database now holds Item scriptable objects now
you can just make them a singleton in the scene that you initialize as you start the game
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
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
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
Alright, seems like you have the idea here
How to make delay in while?
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
I was thinking about getting the ids from a dictionary OnAfterDeserialize and like put them into my slots somehow
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
delaying a while loop requires coroutines usually, otherwise if you want to do it in update you would make a timer variable to check each update and then compare
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
Do I need to do it on Start? I log the OnAfterDeserialize and it works pretty much everytime scene starts.
Wonder if its reliable
like yes? Task.Delay(3000).Wait();
Usually you want to use unity's methods of waiting as Task may not be as synchronized as you want it.
I think there is a more Unity friendly Task method that was added recently
You also have these https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html but as it states you may just want to use a coroutine
Thank You!
but if you do want that frametime sync, usually you do want it to be comparing frametime each frame
I resolve everything with my load screen and it seems to work fine. I usually have it referenced by my gamemanager too
Ah I see. I do not know about using singletons and game managers yet 😄
Gotta learn those some day
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.
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
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
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.
oo I saw that Resources looad thing while messing with the Scriptable objects as well. Could not understand what it does though
by the name I set or? Like the asset's name
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;
}
}
}
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
this is in my GameController class
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void OnLoad()
{
Instance.Initialize();
}
Uhh lots to learn lots to learn
I'd consider making yourself a GameManager singleton as it's even suggested by Unity itself
Not sure how Wait works but await Task.Delay(...) in an async method would work
Yess I will make sure to do that once I set this saving and loading
You never delay in an Update method (or anything called by an Update method)
This freezes the game.
You can await a delay in an async method, or use coroutines to delay running something
Is it possible to instantiate prefabs from inside a list?
Sure.
a List<T> can give you a T
so a List<MyComponent> can you give you a MyComponent, and you can instantiate that
I create it whis Invoke, but it it is activated only once
Ahh nice thanks
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
program start whis invoke method?
no, you use StartCoroutine(SpawnStuff()); to start running the coroutine.
You could do that in your component's Start method
thank you
its problem whis project?
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.
i remove it
thank you
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
im following this tutorial but it doesnt give me the weapon options
Thanks, this solved my issue
"The" weapon options?
"the weapon options?"
thats probably Scriptable Objects
so when he clicks create there is so section that says weapon like in the pick
I see Weapon as the first item in that menu
thats a picture from the tutorail
How should we know that
you either missed a step/video or it didn't compile code cause of error
Probably missing the CreateAssetMenu attribute
i completely forgot how you even do that
show your GunData class
RoomInst = Instantiate(RoomPrefabs[RoomPicker], new Vector3(1, 1, 1));
how come the new vector3 is underlined red. Compiler Error CS1503
riight those things
I never used it before but still cool
to be fair I probably could for like projectiles
Scriptable Objects are insanely powerful in unity
but I usually just copy paste pre-existing projectiles anyway soooo
I just never got around to using them, not yet at least
yeah once you start getting used to them, they have many good usecases
ah yes
You have compile errors as I suspected
anyway configure your IDE
!vscode
hah
you lose track after a while
LOL the timing
fair
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 ?
ok i was using visual code studio already @rich adder
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
Is this unity related? 🤔
@verbal dome more c# related
Did you look for tutorials?
And !learn is recommended
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Probably wanna check out the C# server
!csharp
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
ah ty i didnt have one, 😄
Yes I'm aware, but you need to configure it
also he has camera holder and i dont but i dont know how i would make that work
You have clear syntax errors
his is irrelevant right now, fix your code editor first
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 ?
this isn't the only steps
yeah ive done everything else
did you read the full page
yeah you gotta remove Visual Studio code editor
remove engineer package iirc
or click Unlock, you should be able to click Unlock on the page of package
ok find the Visual Studio Editor one and make sure its installed and make sure the Visual Studio Code one is gone
is engineering package removed ?looks like its not . Screenshot it
you have to remove the engineering feature first
you have not removed the engineering feature
you are on unity 2021 arent you
im not sure i just installed it off the website a few days ago
how are you not sure, it literally tells you in the application titlebar lol
oh its 2022
ohh ok . so is vscode highlighting error now?
you can click regen project files first maybe in Unity
setup failed
can you be slightly more specific
well, it's not
and what is the error, then?
the same
oh mb
yerp
ok its installed but it still saying i need a net sdk
restart your computer
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
no i mean the sdk ones
screenshot your entire VSCode window
try regen project files in unity and open script again (open script from unity)
i'm not sure you actually installed anything
here, run this:
dotnet --info
show me the output -- most importantly, the "Host: " section that tells you which version of .net is being run
this did not include the part I'm looking for
expand the terminal area so you can see more at once
This is, once again, not what I'm asking for
If dotnet --info didn't produce a Host: section then please just say that
ye i was just wondering if it had anything to do with it
what about dotnet --list-sdks
you have the runtime but not sdk it seems
But you installed the SDK for .NET 8
ohh
I haven't had to do this manually on Windows before so I'm unfamiliar with the process
its not your fault, is windows being silly
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)
I'm actually using .NET 8 in VSCode, but I have .NET 6 on my path
I suspect it'll work if you go download the SDK for .NET 7
net 7.0 is out of support version do i still use it
I'd just give it a try
I guess it'd make the most sense to remove .NET 7 entirely and install .NET 8
Yes I'd run the cleanup tool
https://learn.microsoft.com/en-us/dotnet/core/additional-tools/uninstall-tool?tabs=windows
Can i ask for help with my program here?
is it a unity coding question?
yes
go for it
Im new to unity and c# and im trying to learn how to configure solid objects and collision with player.
this is currently my code: https://pastebin.com/Uh5mkHmx
the problem in having is that when the player collides with the object on the SolidObjects layer. it can't move away xD
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the player gets stuck
You could just add a collider to the object instead of checking for collision manually
yea but how do i use that?
This approach is flawed anyway, as you noticed. If it goes into another object, you give it no chance to move away
You know how to add a collider to an object?
I assume yes since you are already checking for collider overlaps
yea i do, but won't i still have the same problem?
you're already moving the velocity on rigidbody, you don't need anything else other than solid colliders
No, the physics engine will separate the colliders and modify the velocity automatically
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?
why not just make Button[]
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?
You should reference the thing you actually need, yes
and if you need both the Text component and the Button component, you should create a new component that has fields for both
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.
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
@verbal dome with this? rigidbody.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
The main thing is to add a collider2d component to the player. Did you do that?
But yes, you might also want continuous collision detection
ok yea
Unrelated to the problem though
Depends on your game. Boxes might get stuck easier as they have corners
Circle or capsule are alternatives
oh yea i found out
much better xD
only problem now is that the world starts rotating when i hit it from an angle
Huh
im still getting the same errors
did you completely uninstall .NET and then install the .NET 7 SDK?
How? lol
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
Ok
Seems easy to fix, can you send a quick video
fixed it with freezeRotation, so we're good
show me the result of running dotnet --info
Pretty common with rigidbodies. Angular velocity
i swear i have tried it like 3 times
and let me see the Host: section
thats the whole thing
scroll up
no, you should not
this appearse to be the same version of .NET that you started with
what did you actually do to uninstall and reinstall it?
i installed the cleanup and activated it
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
Got it working, thank you so much all
this is what I see, for example
copy the entire output and share it with a paste site like https://gdl.space
this looks wrong
screenshot the entire output window
the entire window, including the dropdown at the top
you are probably looking at the wrong output
that is not "C#"
that is "C# LSP Trace Logs"
pick C# and then share the entire output log
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
..did this mean the same errors from unity?
nah i mean the .net errors
because the C# output looks fine
i got this too
but I see that the project failed to activate
well the main thing i was trying to do was this
google suggests this is an error you'd see in visual studio
hm, consider this:
close VSCode
go to the root of your project and delete the .csproj files
the what
as well as the .sln file
do you know what a file extension is
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
and again that
delete the .csproj files and the .sln file, which will be named after your project
i made 2d array how i make it not null inside entries
then, in unity, regenerate the project files from the External Tools window
which bit
"inside entries"?
both of those files at the bottom
Assembly-CSharp and "My project (1).sln"
Put some effort into explaining your problem for once god damnit
i see that windows is hiding the file extensions
do i restart unity
If the array has null entries then you haven't assigned anything to them
No, but you need to regenerate project files from the External Tools menu after doing this
Then you need to double click a script asset to open VSCode
bro im getting the same things
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)
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
If it's an array of arrays, then it's going to be filled with nulls by default. Array is a reference type and the default is null
it would be ideal to have a working code editor
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
i think ill try it tommrow its getting late now
alguien habla español???
Where’s the best place to learn coding?
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?
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?
Show the code that you tried with OverlapPointAll
It should work for this usecase
Rigidbody controllers are not easy to make. To me it sounds like you are directly modifying the velocity, which would make it seem stuck on the wall when walking
I would make the velocity change weaker or nonexistent when you are on a steep wall
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
Hmm not sure, could you put that in a paste site, its really hard to read on mobile
And might also wanna try asking tomorrow when most people arent sleeping
Btw, there also seems to be Collider2D.OverlapPoint if you want to check if the point is on a specific collider
that's being used here
I don't see OverlapPointAll anywhere, though, which is confusing me a bit
Oh I can send you my overlap point all version
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?
correct
Oh woops
They said Physics2D.OverlapPoint in the first question so I just assumed
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
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.
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.
you can sanity check this by manually adding a 2D collider in the spot you're doing the query at
the code should find that collider
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?
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
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.
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
Ya I just turned on isTrigger for the test collider we added and it works fine too xD confusion
you could make it a non-trigger and then see if the player actually bumps into anything
I'm currently doubting that your tilemap collider is actually covering any space at all right now
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.
OverlapPointAll doesn't care about the layer your component happens to be on
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.
yes
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
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
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
no prob :p
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());
}
}
}
thanks for the suggestion. I got a basic system for this working using some raycasting but I now realize how difficult it's going to be to program with each edge case in mind. instead, is there anyway to be able to have a character controller also work with physics?
it looks like, for the second error, you have two methods (functions) with the same name StartAttack. You probably want to rename one of them if they do different things.
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
All of those mean that the respective variable is null (doesn't exist).
That is some code
Null errors are always the same, there is a shitton that can be null there
but how can i solve it?
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?
is it something on inspector or is in the code
I think it'd be in the code unless ItemAssets is something in the inspector
You need to debug and find that out for yourself. There are so many parts there that can be null
item assets its all good
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
You have been told how to share code before...
None of the messages you just sent are the right way
What's the best way to pause certain objects/ui/animation while keeping some objects moving?
make script to pause those specific objects
https://unity.huh.how/references
A singleton is usually a good choice for what nav said.
Could have multiple pause states or events for the different sets of of objects you want to pause if it is complex
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
Have you read the docs? Are you setting it to false?
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?
ah wow
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.
what z-position is your ground at
Its at z=0
and your camera?
about 3
your ground is behind the camera
@final plover ^^
ah thx
you typically want to stick your camera at -10 so that doesn't happen
y'all
im lowkey understanding it
like ngl this coding shit kinda easy
(prob gonna regret that alter on)
this isn't unity 
This is C#
But this wasn't a question
then it breaks both rules
Then you should have said "this isn't a question
"
both apply, it doesn't matter which one I say 

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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
whats the point of that whole duration = frameRate/(60 * 1000000) these are all magic numbers.
You are also starting a coroutine every single frame, so its gonna be "fighting" over where to set the position when multiple are running. In this case i suspect you probably have 2 running at all times since these magic numbers are so small that elapsedTime will quickly be greater than duration
Huh, disabling the lerp changes nothing, so you are right with elapsedTime being greater instantly. How can I make it follow the player without stuttering with the frame rate?
you dont need the framerate at all, im not sure how you even decided on such formula. you're already using update, just MoveTowards every frame with deltaTime as your difference in time.
you mean like this? cs void MoveTo(Vector3 destination) { transform.position = Vector3.MoveTowards(transform.position, destination, Time.deltaTime * 10); }
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...
You shouldn't wiki that, look up official documents as they are very nicely documented
Also this video above ^
sure but no need for the magic numbers still, serialize a number for that 10 so you can adjust the speed. Also this may still fall behind so you can adjust the speed based on how far it is
"delta" is commonly used term for "difference between two values"
thx!
In this case it's time difference between current and previous frame
oohhh
i thought its second and frame
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)
Yeah, it falls behind a lot, how could I adjust the speed? It lags behind a bit when it starts far away: https://streamable.com/4jew6t
- those would be variables not classes
- walkspeed = runspeed for assigning values, == means comparison
- I guess? Depends on how you use it
- Have a variable for speed
- Have two serialized variables for walkSpeed and sprintSpeed
- Set speed to walkSpeed by default and to sprintSpeed when sprinting
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?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ahh so it could work then? aight imma find the working script for it
Also I would make third variable called current speed
And assign value of walk speed or running speed to current speed depending on what's being used
And move my object using currentspeed
well you can adjust it, if you store it in a variable. its just multiplication so im not really sure what you're asking
so if shift is pressed then current speed is equal to runspeed and if not then its equal to walk speed?
Yep
ok thx
You can use object pools if you're worried about performance issues
Yeah I'm using pools for everything else that gets spawned throughout the game, but it wouldn't be beneficial when initially generating the level as none of the 'map' items get removed etc.
You're instantiating maps randomly, all using same items?
Also object pooling is never about "removing" items , I'm concerned
So, increase the speed variable based on how far the object is from the target position?
if you want to, yes
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.
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)?
cinemachine
Ohhh. Never got into cinemachine but I guess it's time. 🙂
Thanks @rich adder
Is something like this possible? An abstract class thats able to do a coroutine?
Yes but you can premake the pools instead of instantiating at runtime
Say you need 500 trees to be randomly spawned in the game, premake the pool of 500 trees and spawn them at runtime
you didn't make it virtual though
how can you override
huh? Okay, I'm massively confused now, because building the pool still needs to instantiate the 500 objects (in your example) at runtime.
Also make it abstract ienumerator if it's going to be implemented in every inherited child
Sorry I'm not sure what it means, so I need to make the handlestate coroutine public virtual override?
Not really no. You create the objects in scene beforehand and save them in the pool.
An asset that let's you do this effortlessly is LeanPool. You can check it out as well
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual
Probably should readup on the thing you are using before you use it incorrectly
ok
Remove virtual from the inherited class
Virtual only needs to be added in parent class, but it already has abstract so it's no longer necessary
Got it thanks
yes abstract becomes similiar to Interface
I've only worked with interfaces in place of these before but i figure this is a better approach for serialization
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 ?
the difference here is inheritance vs composing
you can only inherit one, but you can implement many interfaces
thats true actually
no one knows anything about the setup so this is unanswerable, also networking questions go in #archived-networking
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
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
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.
if they are spawning the objects at the start of the scene, pooling does literally nothing here
Instantiating at start would still be slower than having them preloaded and just enabling no?
The scene needs to instantiate them when it loads as well
profile to see whats really taking the longest. unfortunately its likely gonna be Instantiate, which you cant do anything about unless you can spawn less objects. Make a loading screen and problem solved 🪄
i think you have a misunderstanding at what pooling is, you dont magically just get the items. You have to actually instantiate it at some point. Whether thats at the start of the game, or the start of a scene doesnt matter
it would just be moving the lag from one area to another
Ye ye I forgot scenes instantiate all object when loading
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
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
transform field?
you have the prefab selected not the gameObject in the hierarchy
also not a code question
@languid spire
whats up
Can you help me on networking ?
In PC host and client perfectly working but in mobile not find the server.
#📖┃code-of-conduct Do NOT ping people into your conversation.
And no, I generally do not help people with Networking problems

where should i ask this questions?
you have asked it here and I have told you the answer
Oh yeah there will be a loading screen. The question wasn't so much about perfomance tbh, as all this happens on level start etc. and only happens once and nothing in the map gets destroyed. Was just a curiousity as to whether there was a better way than just going through each 'layer' of object and instantiating like I've got coded is all.
not really, cause you missunderstood me, so i asked where to ask these questions since you said it was in the wrong chat. i thought i had done something wrong with the code.
ok then #💻┃unity-talk and give a more detailed explanation of what your problem is
i dont see anything wrong with that specifically. if you want to spawn some of everything, youll need to go through each kind of object you want to spawn.
Yeah, that's what I usually do, create a method for each item type and then just call them in turn. It's very methodical etc. and it does work great, just looking at it and it just seems a little inelegant if that makes sense? And tbh, pretty much everytime I post code somebody always seems to find something I'm doing wrong. lol. So was just a curiosity more than anything
You could define what spawns via scriptable objects which would move some of the work to editor instead. i dont really remember what your code was but this would turn it into a shorter code solution with the same outcome. Would be more friendly for others to work with as well, and support adding more items without changing the code
Aaah, that's interesting. Although I'm still struggling a bit on how to use SO's properly, but that's definitely something I could look into.
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?
at first I didnt really understand the use for SO too. i think the intended use case is so simple that once you get it, its almost like "is that it?"
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
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.)
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
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.
Anyone know how to fix this?
Ok, that looks like a Unity bug, restarting Unity should clear it
yes
Alright Thanks.
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;
}
}
}
mistake here I believe
for (int i = 0; i < groundItemSOs[i].groundItemPrefabs.Length; i++)
Ah yeah, the groundItemSOs[i] should be gSO (on all). oopsy. lol.
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
the point system doesn't work.
how can you expect to read the value of point if you destroy the gamobject that it is on?
you must also be getting errors which you don't even care to mention
First step is to configure your code editor so you get the full range of features it provides
!vs
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)
Do that first, then come back, this is a required step to get help here
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
Because one of your animations assigns its position
Yep that's an animator issue
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.
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)
Also make sure you send your code in a text form. I have opened the image's link and it's very blurry and hard to read
How to make it so that if an object touches another object with the same name, it divade?
how do i do that?
!code;
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Those are 2 problems, solve them one at a time. Objects colliding with the same name and dividing.
One is just looking up collisions in Unity and 1 is just instantiating another object of the same type.
I can't find documentation about colliding object
lol i seek if touch
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
And you don't think the documentation of collisions explain the if touch thing?
i found it
🎉
Also read what SPR2 said, using name's of gameobjects for logic isn't a good idea.
private void OnTriggerEnter2D(Collider2D collision)👌
how can I disable animator with script?
As long as you use trigger colliders and 2D that's the correct method yeah.
Did you try googling this exact question first?
With the word "unity"
no i didnt lol
i am dumb
its right?
Apparently not
how make right?
Mind showing more of the code instead of one line?
The parameter is named collision, not other
Which should probably be renamed to collider, since that's what it really is
oh, thanks
its?
Syntax error, 'word' expected after "its"
Yes that is valid. You can give it any name you want, like other variables
Im sorry
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
the point system doesn't work.
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?
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
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)
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
discussion of which is prohibited by #📖┃code-of-conduct
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
how i get dictionary by index
one of those is in an Editor folder
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
Oh so the fact that its editor code blocks it off 🤔
Right.
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
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
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
yeah -- if you want part of a class to still exist in the build, then that's the way to go
also does dictionary even keeps order i inserted stuff in it
i don't believe it does, i think there might be an OrderedDictionary if you need that
OrderedDictionary doesn't remember the order you inserted items in
oh, maybe I am wrong!
I was thinking of SortedDictionary
yep
[]
Enumerable.ElementAt(int);
yeah no int fails to be passed to string dictionary
boys i dont know what is null here all prefabs are active
double click error see the line
sends me to here
and here
what im i supposted to do
im having this error for 2 days and i cant solve it
Please share code properly
That line on 114 is wild. A lot could be null
weapondata is a script where a keep all weapondata
how can i share the code do you have that site?
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
objectpooling:
https://gdl.space/duheyubowe.cs
weapondata:
https://gdl.space/nojunoxipe.cs
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
Find on that line what is null
that is the problem friend i can find it nothing is null in my game 🥲
You get NullReferenceException when you attempt to access something (using the .) on a value that is null
Do you know how to use breakpoints and the debugger?
It would tell you very fast what is null
Otherwise, put down some debug.logs
what to see the prefabs?
What?
Breakpoints are in code
where can i check in the inspector or is something on the code
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
How to fix this?
Can't know, it's only at run-time that you can ensure things are not null. In that class for example, parent, weaponType, weaponSprite, description could be null
Attempting to do things on them when they're null would result in a NullReferenceException
Learn how to debug, and debug
Not much we can say beyond that
If it does not come from your own code, AND that it does not break the editor or your game, you can most likely ignore them.
ok so what kind of data storage will be best for finding entry of largest index smaller than x number
Are the indices contiguous or sparse? Do you have every number in order or are they indices all arbitrary numbers?
not in order
Fine
well they are increasing but there are numbers missing
How often are you going to need to do this search, and approximately how many entries do you expect to have to search
1000 and maybe 100k of searches
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
Have you debugged
this is very important to me
We are not at your computer...
send the error and what you've already tried bro
i can send my project man
💀
It's just above
Learn how to debug, it's easy
Fuck no
ok man
ah nvm
Just add the debugs we said.
TRY
what debugs?
Debug.Log on all the things that could be null
- http://unity.huh.how/debugging
- https://docs.microsoft.com/en-us/visualstudio/debugger/debugger-feature-tour?view=vs-2019 (if you're using Visual Studio)
do these people live life with a blindfold on
split that line into more lines so editor specifies function that errors out
That was suggested a while ago, and would be a good idea
They seem to be ignoring all suggestions though unfortunately
Yes
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.
its on line 166
What is line 166
Follow the same troubleshooting steps. Stack trace to locate the line of code, then check what's null and make it not null
Do not share code as screenshots, as I have told you three or four times within two days
too many functions that can error out split them to 10 lines
why?
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
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
Cannot copy text from a screenshot to paste it back here, for example
Like 6 things on that line could be null
i miss times when editor said exact character count from where error starts
oh sorry about that
One thing, never use Find
At least do the tag or type variety
Better to drag and drop whenever possible
It does for syntax errors. Runtime errors can't have that because the code doesn't actually exist in that state, it's machine code by then
That's only available for compiler errors, column index info is stripped out from compiled code.
In some cases the debugger tells you what exectly went wrong
I think that is Transform.Find
eg.
Ah fair. I would still avoid string based search. But yeah. Not as bad
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


