#đ»âcode-beginner
1 messages · Page 785 of 1
there's no magic link we have
i mean thats fine i was just wondering, but thanks anyways
wait - I found this tutorial https://www.youtube.com/watch?v=ZEtKg9AyEJc . I'm not that knowledgeable on unity, but does it seem pretty substantial? That it might take a couple weeks to make at least?
Learn Unity 6 and C# by making a 2D game where you fight off enemies to protect a little girl. Timecodes below -đ
âș Complete RPG course - https://unityalexdev.com/rpg
âș Complete courses for beginners at - https://unityalexdev.com/#courses
âș I've opened a Discord server, join us!â - http://unityalexdev.com/discord
Important link...
sure
You're probably not going to find a tutorial that solves all your problems. The idea is to learn from many sources and synthesize them into your own internal understanding of the process, rather than just parroting videos other people have made
you're right
i guess i can just start with this and try adding stuff later
You don't need to vet a tutorial to see if it's "worth your time", just learn from anything you find
Just not the ai
Well, you do need to learn "Stay the hell away from it" so there is still something to learn there
but yes, stick to actual sources that have actual knowledge
can some one can help me with making my ai use a sward? https://paste.mod.gg/zniibrhyhtkg/0
A tool for sharing your source code with the world!
love ambiguous help requests with minimal context
what more you need
pretty sure they just want someone to hold their hand and make it for them
As an example, here's a completely valid answer to the question, as posed:
Make a "sward" object as a child of the player. Done.
If you want more than that, you will need to actually say what you want
also you sent your code
but it has nothing to do with swords of any kind?
so the question is did you even attempt to do it on your own
or did you decide hey ill have these guys on discord do it for me?
i have no idea how
so break it down
how do i do it without knowing how
you learn how to do it
yeah where
first you break down your problem into multiple stages
the internet is a vast resource of knowledge
First step is to actually know what you want
you need to start be deciding what it means to "use a sward"
yeah ok ill go search it i did alrady but more deap ig
i doubt you did but whatever
that he will reconize when the player is in front of him and hit him with the sowrd
Is there a way to make decals only display on certain objects? I have a drill where I drill into a ceiling and I use a projector for the hole mark. But when the drill is still close up to the wall, the decal shows up on the drill. I created a rendering layer called decal, and set the projector's rendering layers to the decal layer, then I set the walls to have the decal rendering layer and no other objects have it. But still the decals are projected on other objects.
you need to break it down into actionable steps first because just searching "how to make ai use a sward" isn't going to get you anywhere. you need to first define what that means, break it down into smaller steps that you can research and put that knowledge together after researching how to complete each step
incredible juxtopositing within this screenshot
this is literally the worst possible way to research anything
There you go, that's more actionable. Now, you need to find out how to detect when an object is in front of another. Then you need to decide what "hit him with the sword" means
yes you all right i will break it down and serch it like that thank you
Hi, People
I need, Sanity with someone who can explain the "Coroutine" thing
Because I have a lot of issue with it, but I want to use that technologie, I know what is for (like a simulator of waiting for script) but I need a person how can help me with my bugs
Do you have a specific question about them, or you're just completely lost on the whole concept?
what bugs do you have?
Share your code and explain what's going on
Coroutines, once started with StartCoroutine, run like normal functions, one line at a time, top to bottom, until they hit a yield statement. That statement will then pause the coroutine and go back to the line after StartCoroutine and resume from there, until the yield instruction tells it to resume. The simplest yield instruction is yield return null, which will resume the coroutine from that spot next frame.
Context : I create a Computer in my 2D isométric game, the player click on collider2D, and bom the prefab computer Spawn.
The thing is, its just a text thing right now, So, for that, I use Addressable for load a JSON file who have all the text that I will need.
And the principal issue is 2 thing, 1. A error that appair (but I thing I fix it somehow) that saw "I am Coroutine, I can't work because your gameobject (the computer) is Inactive !" But I try like, FORCE the unity to active it even I saw in my inspector the gameobject never been desactivate, but yea that thing break my mind, and its not the worse.
And Second one its the .. loss of my data, Like in my script That I will show you, I stock my text from JSON to a Variable that is a tab in a tab, and the thing that, its working good, but when Im outside of the function, its .. become null ? I will show you my code
I create a Computer in my 2D isométric game, the player click on collider2D, and bom the prefab computer Spawn.
Nothing about this sounds like something that you would need a coroutine for.
A error that appair (but I thing I fix it somehow) that saw "I am Coroutine, I can't work because your gameobject (the computer) is Inactive !"
Can you share the code you used and the actual error message you saw?
loss of my data, Like in my script That I will show you, I stock my text from JSON to a Variable that is a tab in a tab, and the thing that, its working good, but when Im outside of the function, its .. become null ?
This sounds like a totally separate issue
I use the Coroutine for give time to Addressable a moment to Load a 4 line of Json, yea sound stupid but im new and IA are not so useful
ok yeah you'll need to show your code and any error messages you saw
what are you invoking the coroutine on?
I have 3 script, script one :
you may be trying to start the coroutine on the computer prefab itself
and I'm pretty sure that prefabs do not count as being active
!code
đ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
đ 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.
ooooh
ok wait
gonna try that
A tool for sharing your source code with the world!
Here
I hope its work
- In you will found Comparator, his job its to Compare Tags of GameObject, I create a Point and Click so I need to know what is for.
- ComputerManager its the Brain of the Computer, he will be the bridge of the player input and the Computer.
- ComputerTextManager a Brain too for Text of the Computer
Been trying without the prefab, the problem stay sadly the same
Im sorry, I don't think I understand the question
What object is calling StartCoroutine
I have a lot of StartCoroutine
the one you have issues with
check its stacktrace and see which line it's coming from
oh
then you can work backwards from there
with the ComputerManager and the TextManagerComputer
From ComputerManager : IEnumerator Start()
{
yield return new WaitUntil(() => _ComputerTextManager.IsDataReady);
_ComputerTextManager.Load(ComputerTextManager.Sections.Login, 0);
}
public void Launch()
{
Start();
}
you aren't starting a coroutine there
and the TextManagerComputer :
private void OnJsonLoaded(AsyncOperationHandle<TextAsset> handle)
{
if (handle.Status != AsyncOperationStatus.Succeeded)
{
Debug.LogError("Failed to load JSON Addressable.");
return;
}
try
{
CurrentData = JsonConvert.DeserializeObject<SectionsData>(handle.Result.text);
Debug.Log("JSON chargé avec succÚs !");
}
catch (System.Exception e)
{
Debug.LogError("JSON parsing error:\n" + e);
}
}
when you call Start(), you create an object: but just creating it does not do anything
Yea, its say that my gameobject its not active
Sorry :c
it has to get passed to StartCoroutine for Unity to start running through it
Im paniking
what is saying that
A error from the Coroutine System (not mine)
wait I will found it
the only StartCoroutine in your code is on line 103 of ComputerTextManager.cs
StartCoroutine(...) is equivalent to writing this.StartCoroutine(...) -- you are calling the method on a specific object
Importantly, if this object is a prefab (and not a copy of the prefab), this won't work
You need to instantiate the computer, then start coroutines on that copy's components
you cannot start coroutines on the prefab's components
Coroutine couldn't be started because the the game object 'Computer' is inactive!
UnityEngine.MonoBehaviour:StartCoroutine (System.Collections.IEnumerator)
ComputerManager:Launch () (at Assets/Script/BuildIn/Machine/Computer/Manager/ComputerManager.cs:92)
Comparator:MachineCompare (UnityEngine.Collider2D) (at Assets/Script/Interaction/Zone/Player/Comparator.cs:156)
PlayerControl:OnTrigger (UnityEngine.InputSystem.InputAction/CallbackContext) (at Assets/Script/Input Manage/Player/global/PlayerControl.cs:176)
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr)
that is when I add a "StartCoroutine(Start())"
You are calling Launch() on the prefab itself
the prefab object doesn't really exist
it acts like a deactivated game object
you need to be calling Launch on an instance of the prefab
the prefab does exist, but not in a scene
you need something in a scene
I would expect this prefab to be placed in the scene
currently, your code does this...
public bool MachineCompare(Collider2D hit)
{
GameObject obj = hit.GetComponentInParent<Transform>().gameObject; // met une sécurité ici
if (obj.CompareTag("Computer"))
{
if (GetReferenceComputerManager())
{
_ComputerManager.Launch();
}
else
{
Debug.Log("Null!");
}
return true;
}
return false;
}
Its "place" by Addressable
yep, its mine
It's looking for an object in the scene, but then you just go to _ComputerManager and call Launch() on it
If ComputerManager is a "singleton" â something that there is only ever one copy of â you should instantiate it and then use the resulting copy
If it isn't â so each computer in your scene needs its own ComputerManager â then it should be attached to those computer objects
So, Basicly, if I understand
My problem its that a Prefab its a ghost for Unity, and for that, I need to create a Gameobject that can be the Brain of the prefab ?
A prefab is a GameObject that lives in a file
Files cannot run coroutines
You need to run the coroutine on an object in the scene
ok so
That I can fixe it, Thanks you
but I need a understanding with the last bug
The "Lost Value" of ComputerTextManager
private void OnJsonLoaded(AsyncOperationHandle<TextAsset> handle)
{
if (handle.Status != AsyncOperationStatus.Succeeded)
{
Debug.LogError("Failed to load JSON Addressable.");
return;
}
try
{
CurrentData = JsonConvert.DeserializeObject<SectionsData>(handle.Result.text);
Debug.Log("JSON chargé avec succÚs !");
}
catch (System.Exception e)
{
Debug.LogError("JSON parsing error:\n" + e);
}
}
here to be precise, with CurrentData
I trying Debug.Log with it, and its show all my data, even when I modify the JSON
But when Im out of that function, the CurrentData Lose all his data
consider putting your description of the issue into a single message please
my bad, a bad habit of mine
Where do you declare the CurrentData variable
private string Addressable { get; set; } = "MachineComputerText";
private SectionsData CurrentData { get; set; }
private Coroutine TypeCoroutine;
private AsyncOperationHandle<TextAsset> handle;
public bool IsDataReady => CurrentData != null;
- are you assigning to it anywhere else
- are you sure you're checking in the same instance
Okay so that would be an object scope variable. That means it doesn't get lost when you leave the function
all in that file : https://paste.mod.gg/vsiornhhbtdb/2
But 1. No
2. What is a instance ?
A tool for sharing your source code with the world!
Its a normal world
But in my unity, its losing
Like what I have its not normal
No, it isn't. Either you're overwriting it somewhere between when you set it and when you check it, or you're looking at a different object that didn't have OnJsonLoaded called on it
My english its not my primary language, sorry if its bad-
a class is like a blueprint. when you instantiate that class (in unity, when you attach a component to a gameobject) you create an instance of the class. each instance exists separately from every other instance
public bool Load(Sections section, int index, float delay = 1f, float delayPerChar = 0.03f)
{
if (CurrentData == null)
{
Debug.LogWarning("JSON not ready yet.");
return false;
}
Data[] array = section switch
{
Sections.Starting => CurrentData.Starting,
Sections.Login => CurrentData.Login,
_ => null
};
if (array == null || array.Length == 0)
{
Debug.LogError($"Section {section} is empty or missing.");
return false;
}
if (index < 0 || index >= array.Length)
{
Debug.LogError($"Index {index} out of range for {section}. Length={array.Length}");
return false;
}
if (TypeCoroutine != null)
{
Debug.Log("Il est nulle le Coroutine");
StopCoroutine(TypeCoroutine);
}
TypeCoroutine = StartCoroutine(
TypewriterEffectWithDelay(array[index].text, delay, delayPerChar)
);
return true;
}
Here is the only function that use CurrentData
and where do you call OnJsonLoaded
in the same file
that doesn't help
So either you are setting CurrentData to something else, or the thing you're calling Load on is not the same thing you're calling OnJsonLoaded on
what method chain links OnJsonLoaded to Load
yea, in the Awake()
no, you aren't calling it there.
Load its to Load the text, but I have a Event Variable that in the coroutine of ComputerManager make the "click" event wait until the function OnJSLoad finish his work
Where are you calling OnJsonLoaded and what object are you calling it on?
Where are you calling Load and what object are you calling it on?
?
private void Awake()
{
handle = Addressables.LoadAssetAsync<TextAsset>(Addressable);
handle.Completed += OnJsonLoaded;
}
I can bad understand your question, sorry about that
Okay, so, this will run OnJsonLoaded on this object when handle.Completed is invoked.
Now what about Load
What calls Load
@magic temple what info is telling you that CurrentData is gone? the JSON not ready yet. log is triggering?
(they shared the complete code above btw. that's gonna be much easier than this game of telephone)
Here is the full script (modify for discord) :
private void Awake()
{
handle = Addressables.LoadAssetAsync<TextAsset>(Addressable);
handle.Completed += OnJsonLoaded;
}
private void OnJsonLoaded(AsyncOperationHandle<TextAsset> handle)
{
if (handle.Status != AsyncOperationStatus.Succeeded)
{
Debug.LogError("Failed to load JSON Addressable.");
return;
}
try
{
CurrentData = JsonConvert.DeserializeObject<SectionsData>(handle.Result.text);
Debug.Log("JSON chargé avec succÚs !");
}
catch (System.Exception e)
{
Debug.LogError("JSON parsing error:\n" + e);
}
}
public bool Load(Sections section, int index, float delay = 1f, float delayPerChar = 0.03f)
{
if (CurrentData == null)
{
Debug.LogWarning("JSON not ready yet.");
return false;
}
Data[] array = section switch
{
Sections.Starting => CurrentData.Starting,
Sections.Login => CurrentData.Login,
_ => null
};
if (array == null || array.Length == 0)
{
Debug.LogError($"Section {section} is empty or missing.");
return false;
}
if (index < 0 || index >= array.Length)
{
Debug.LogError($"Index {index} out of range for {section}. Length={array.Length}");
return false;
}
if (TypeCoroutine != null)
{
Debug.Log("Il est nulle le Coroutine");
StopCoroutine(TypeCoroutine);
}
TypeCoroutine = StartCoroutine(
TypewriterEffectWithDelay(array[index].text, delay, delayPerChar)
);
return true;
}
}
It doesn't include where they call the function from
So what calls Load
it does
The :
if (CurrentData == null)
{
Debug.LogWarning("JSON not ready yet.");
return false;
}```
in Load
A tool for sharing your source code with the world!
ComputerManager.cs:88
here
and does that trigger
yes
hehe
I put a lot of that thing that I call 'Dog cage'
like a security thing
Okay, so _ComputerTextManager is the object that runs Load. Which object is that referring to?
have you tried checking CurrentData after you load it
...the guard clauses?
a empty gameobject in the prefab
In the prefab
well, obviously not empty
in the prefab or in the prefab instance?
which means it can't have had OnJsonLoaded called on it
i mean, obviously the same object that is being checked for IsDataReady 2 lines above, so...
When I start the game, the prefab charge, and the Text from the JSon are loaded in my view of player
but when I trying like, control the text, the CurrentData say to me that its null
that is the issue
this doesn't answer any of our questions
In.. the prefab Familly
How about you share the stack trace of the thing that says its null
that's.. not a valid answer
that's unrelated
I terribly sorry
is it in an instance of the prefab, in a scene
The prefab file, and the instance in the scene are not the same object
They are two different objects that both have this script on them
You are calling OnJsonLoaded on one of them, and then checking the other one to see if the data is set
And, since it's a different object, that one doesn't have CurrentData set
I gonna show you I think
here, Computer have the ComputerManager Script, annd ComputerTextManager have the .. computerTextManager
.. Im so confuse
we are asking whether or not the object is in the scene
we don't particularly care about the specific hierarchy
Not when I not "trigger it" with Comparator, when its call, Comparator.cs Call a Addressable to be in the scene ?
public bool MachineCompare(Collider2D hit)
{
GameObject obj = hit.GetComponentInParent<Transform>().gameObject; // met une sécurité ici
if (obj.CompareTag("Computer"))
{
if (GetReferenceComputerManager())
{
_ComputerManager.Launch();
}
else
{
Debug.Log("Null!");
}
return true;
}
return false;
}
that code is not relevant
do you have instances of these components in the scene or not
Say me a exemple
do you know what a scene is
Is there an object with a ComputerTextManager component in the scene
ye
No
that is the main cause of your issues
Then you have nothing with CurrentData set
Because Awake does not run on prefabs
When why I have my Text from the JSon in the TextMeshPro in Computer ?
what are you even looking at
If I can't have the information, how I see it
Probably because one of the things you've said so far is a lie
And I have no idea what
because I cannot see what you see
and you have to actually provide information
jesus christ just take a screenshot of your entire unity window
I can, like, show you in a vocal or something
no
Brother-
theres also no voice chats here
Im not here to lie, im seeing what im seeing
maybe you didn't knowingly lie, but something you've said is wrong
When I click on the trigger, the prefab spawn and the text from the json its loaded
what are you clicking on
Collider2D
an instance of the prefab in the scene? or what exactly?
that gives me no info at all
wait
I will show you
that little block its my Collider
he have a tag
and Comparator will .. compare that tag
if the tag its correct, the prefab are call
Do you want that I Screen Share ?
no
aww
and to be clear, the computer isn't inside the canvas or the maincamera, right
god
Im new at Unity, Im trying-
the computer isn't inside the object inside your scene named "Canvas" or the object named "MainCamera", correct?
yes
this is basic english
" but its not IN a canvas" and I think I make it thew
cool, then we've established one of the things you've said is correct - the computer is not in the scene. there does not exist a Computer instance, which you need to be able to do things in unity
that is your main issue
alright, when, why use a prefab ?
when you want to use a gameobject as an asset, one you can reuse in multiple places, and you can modify that asset and have that change propagate to all its instances and variants
But then, how is it possible that when the prefab is activated and put on the scene, I can see the text from my JSON in the âGameâ view? Even though it's not supposed to retrieve anything because everything that is read in the JSON and put into a variable is in Awake()?
no clue what you're referring to at this point tbh
is the prefab being instantiated from some other object?
if not,
when the prefab is activated and put on the scene
this just isn't happening.
you also haven't really shared what exactly you're looking at in the gameview
yep, the gameobject Comparator
how can I ?
in Comparator.cs? you don't have any Instantiate calls there.
a screenshot would do
ok, so you have a Computer(clone) there. sounds like that's an instance of your Computer prefab
probably something else is instantiating it
yeah ok, this is starting to make sense.
The only thing installed on Scene is the Empty Comparator game object, which contains the comparator.cs script.
well that's obviously not correct
enlighten me
right now you have 2 instances of the ComputerManager/ComputerTextManager.
one in the prefab, one created later in the scene, at runtime.
the one created in the scene is handling itself. the ComputerManager.Start coroutine is being executed, ComputerTextManager.Awake is being run, etc.
the prefab one is getting its ComputerManager.Start called separately or something, maybe through Launch (which probably should not exist), there's that weird AutoAssignAssetReferences in Comparator. you definitely don't need anything like that
AutoAssignAssetReferences its a Script that I create to Found all my forgetin References, its a security for people that work in my project
sounds like something that would only cause problems tbh
why does something DDOL need to persistently reference something in a specific scene anyways
with serialized references or with singletons where that makes sense
something DDOL like that wouldn't be written for something in a specific scene anyways
and i don't see why you'd instantiate it at runtime, why not just have it in the scene
Because I'm changing scenes, and I want to keep important game objects such as Player or bluidin.
that doesn't really change any of what i said
Well, be more specific.
ive been pretty specific
what you said simply is not relevant to what i said
is Comparator specific to this scene, or is it used for many scenes?
Used for many scenes
The player will go through the scenes for various reasons, so in order to know what it's used for and where it clicked, I need scripts that won't get lost.
then why is it written with stuff specific to this one scene?
? its not only for One scene, its for 'all' scene
public async UniTask<bool> Zone(Collider2D hit)
{
if (!hit)
{
return false;
}
GameObject obj = hit.GetComponentInParent<Transform>().gameObject;
if (obj.CompareTag("GreenZone"))
{
return true;
}
if (obj.CompareTag("RedZone"))
{
return false;
}
if (obj.CompareTag("InteractiveZone"))
{
return await _InteractiveZoneController.OnInteractiveZone(hit);
}
if (UnityDebugLog)
{
Debug.LogWarning("[Comparator](Zone) Aucun tag reconnu.");
}
return false;
}
Like here, its for the scene Outside, Dortory1, Village..
I'm trying to limit scripts, not give each scene its own script, which kills performance.
But what's the point? Why are we having this discussion? It won't help you understand my problem.
MachineCompare seems to be written with just this scene in mind
...you asked... #đ»âcode-beginner message
something like this would not be anywhere near killing performance
I plan to install another machine, so comparing which machine the player interacts with is the purpose of comparator.cs.
Simple does not mean more efficient
efficiency does not matter at this scale
And I have a constant mind of saving every single frame.
that's a very common beginner pitfall, premature optimization will only give you more workload for nonexistant results
Not for me
optimize when you have issues
make it an interface even, IInteractable, check if you've clicked an IInteractable in the player, call the Interact method
the machine implements IInteractable and plays the text when you interact with it, or whatever.
computers are fast. you could have 5000 comparators in the scene and probably not notice any difference at all
if you're looking for peak efficiency then don't make a game at all. it's more efficient to imagine you are playing a game because that doesn't use any of your computer's resources and can run at a framerate that matches the speed of your thoughts
you have other issues to worry about at this stage
make something work before making it good. and making it simple to work with is a very important step to making it work
Hey guys I'm having a few issues with inputs in Unity
I'm really new to the engine so forgive me if I don't understand some things
Basically I have a button and when I click it I have a line to simply log it in the console but no matter what I've tried, nothing works
I don't think we share the same way of thinking. My goal is to rack my brains, understand the very core of Unity, try to understand the issues, and that's what fascinates me, not making infinite loops and hoping no one notices.
simple code makes issues easy to understand. you aren't trying to understand unity here, you're trying to understand issues created from your own convoluted code
- make sure you are referencing the correct buttons and not prefabs or whatever in your variables
- make sure you have an event system in the scene
- make sure that Awake is actually running too
also make sure you've added that component
Is your goal to give your future self more work and headaches and call it âpro devâ? I'm taking things into account right now, as any good developer should.
youre giving yourself more work and a headache now
so what are you really accomplishing here
The goal is to give my future self a vacation, not the other way around.
ok, so design your systems to be easy to work with

even if you created perfect systems and configurations now you will still have other challenges down the line
like this is just the nature of development
I have one object that has a mono behavior for the buttons and I have them referenced here
You're gonna laugh but idek what a prefab is
I'm a complete beginner in this engine
your future self is going to have plenty of vacation time when you abandon the project because you are developing yourself into a corner with all this preemptive microoptimization
sometimes you gotta relax and think "we will burn that bridge when we get there"
So, I sacrifice the player so that I can âreadâ what I've done better?
when did i say that
great! now check the other two points
also what do you mean sacrificing the player
Dude, do you need psychological help?
thats not very nice
i'm saying to think about your systems and use simpler, more direct, more maintainable, easier to debug, methods of referencing other objects
I do have an event system and the music does play so I assume the awake is running?
love the implication that a player would give a shit if a system they dont know about in a game they are playing isnt perfectly optimal
just a reminder clair obscur just won game of the year and it runs like shit
people dont really care anymore
the bar for performance is so low it might as well be a chalk drawing
That's the whole problem with developers, and I'm not the only one saying it: you make life easier for yourselves rather than improving the player experience. Personally, I try to rack my brains as much as possible to offer a game that can run on even the worst PCs, rather than expecting players to have a good computer.
validate that assumption, add a debug log to Awake
The fastest possible code is one that doesn't run
yeah i doubt whatever happening here is going to have such catastrophic performance issues that will make it so that a slightly weaker pc cant run your game.
good thing my suggestions would both make your life easier and your game better, because it would allow you to actually make progress with your game instead of worrying about microoptimization
i'm being realistic. you are doing things out of order in some harebrained attempt at making yourself need to work less later, when you are making your workload now even larger than what it would have been overall if you started with "make it work" before "make it fast"
the order should be make it work -> make it good -> make it fast
otherwise you're going to run into issues now while attempting to make it fast before it even works, then when it isn't good and you need to redesign you need to do even more work
Checks out
youre also optimizing your game for the 1% of the 1% which isnt good
I mean, the guy says to give up all hope or worseâI'm seriously worried.
So what's your data showing how much this affects the system requirements of the game? If you're willing to make a complicated system surely you have analytics of how much it saves, right?
can you show a screenshot of the inspector for the event system you have in your scene
lmao no? they're giving an extreme example that focusing purely on premature optimization will just burn you out
and they're correct
is that what he is saying?
or are you just not listening
Considering how hard we had to explain the difference between a prefab and an instance, you probably shouldn't be worried about efficiency.
Sure thing
and the buttons are attached to the canvas, right?
Yeah
My own PC is crap, so if my game runs on it, that means I've done a good job. Then I'll look for other more advanced tools to ensure precision.
is it a world space canvas or a screenspace canvas?
ok, if you have issues running it on your pc, then start worrying about optimization. anything else is premature
screenspace
And how do you know that what you're doing isn't making it worse
ensure precision.
you'd rather it runs fast more than it running correctly?
What data are you comparing it to?
and your canvas has a Graphic Raycaster on it, yes?
and the images on the buttons do not have "Raycast Target" unchecked?
also i dont think you are being very fair to the people who were helping you for the past hour
Do the buttons visibly respond to the mouse? By default they should change color when you hover or press them
That's probably what it is
Both were checked on
oh wait, sorry had that reversed it must be checked
That's what I do. I start with something basic, and if it works, I make it more complicated, optimize the code, and try to figure out how I can improve it. In short, why are you doubting me on this? It's not the first time I've worked with code.
@magic temple literally everyone here has been a beginner before.
many of us have encountered many of the issues we're referring to. this advice has been from collective experience
Oh, ok yeah they are checked
Yeah, that's what they're supposed to be, you want it checked on things you can click on. Make sure nothing in front of them has that checked
Also no they visibly don't respond to clicks
you keep responding to certain messages as if they are saying something completely different than what they actually are
you immediately become hostile at the slightest bit of valid criticism
I have a graphic raycaster in the canvas and both are checked
and to be clear, you have clicked into the game view before testing any of this, yes? because the game view needs to be focused for the event system to properly work with your input
you have this backwards. you need to improve it before worrying about optimizing it
You might have an invisible hitbox in front of them, try disabling any other objects but the button and their parents, then try to click on them
Is your advice âdo something that works before adding glitter to itâ? Because that's how I work, except that RIGHT NOW I'm in the OPTIMIZATION phase, so it's normal that I'm stuck on it.
you have broken code
what do you mean you're on the optimization phase
you need to make it work first
Okay, so it works as expected, it's just slow?
Avoided addressable, doing something more âthe hard way,â without prefab, without all those coroutines... In short, yes, I went through those steps, and now I'm improving what I've created. Why is it such a big deal to you?
Wait that's what it is omg
I had a fade object over everything and just completely forgot that it blocks inputs
I unchecked raycast target on it and it works, ty guys for the help
As you can tell I'm super new to unity
Is the code broken because I'm optimizing it?
if you consider what you're doing now to be optimization, then yes
Well, thanks you, a advice still a advice
No, its
Like, People
Please, why are we even talk about it
It's good, UI problems got way harder to debug lately. Used to be the window on the bottom of the EventSystem inspector would tell you what you were hovering over and made it easy to debug. Now it's mostly trial and error.
I think it's a URP thing?
My question here is, Why a prefab is 'enable' that has been answer, thanks you for that
come again?
and, why I have acces to my JSON even the Awake of my prefab its not suppose to be activate ?
i gave you advice on how to improve your code, and you've been aggressively denying it because it would make performance worse
that's just not how you should be working
ive already answered you
This is impossible, I can't keep dealing with someone who is belligerent as well as having a language barrier
aggressively ? my excuse, my english its my devil
Where ? I must have missed it.
They linked it
It's the same thing I've said as well. The one that you're loading the JSON on and the one you're trying to read it from are different instances
Question, they are both in the prefab
that's not a question
Good point
you have a Computer prefab (as an asset, in the project) and a Computer prefab instance (in the scene)
both of those each have their own ComputerManager/ComputerTextManager
The prefab file and the instance in the scene are not the same object
I cannot stress this enough
They're two different instances
If you do something to one of them, the other one is unaffected
Im using deepl, hehe
So, Computer, which is cloned on stage and includes my script, the ComputerManager and ComputerTextManager, ComputerManager can have its awake activated, but not ComputerTextManager?
no, the ones in your scene are active, the ones in the prefab are not
... Well, here is, my problem
the core even, My Cloned one say to myself, that he is inactif
and losing his own data
The Cloned one, the one in the scene
yea and you say that ComputerManager its awake, but not ComputerTextManager
if im correct
here ?
yes, and in my initial explanation as well
" right now you have 2 instances of the ComputerManager/ComputerTextManager.
one in the prefab, one created later in the scene, at runtime.
the one created in the scene is handling itself. the ComputerManager.Start coroutine is being executed, ComputerTextManager.Awake is being run, etc.
the prefab one is getting its ComputerManager.Start called separately or something, maybe through Launch (which probably should not exist), there's that weird AutoAssignAssetReferences in Comparator. you definitely don't need anything like that " here ?
what else would i be referring to
btw you can use the eventsystem's raycast into a cache list to check that manually (it's not much to do for it). I use that when debugging ui stuff these days in the rare cases I get a blocking 0 alpha sprite and can't find it 
Good to know! A bit more involved than the old "just look at it" method but definitely useable
Are you alright ?
I mean, right now Im tired, like, really tired, and if I
if I say someting bad, im sorry
i'm irritated because you seem to be intentionally obtuse right now
Well, its not my objectif
I want just to fix a missunderstanding of mine
Still, thanks you for your time
I will, try to make it not a prefab, or something
My excuse, have a good day
sounds like you do want it to be a prefab here, considering you wanted more computers
you just need to treat it correctly
I Know, I try
But, Im searching how to do it
but im sure I will found out
why could this code not work
its suppost to make you move but i just fly or makeweird movements
Try logging w and see if it's doing what you expect
did your keyboard stop working partway through naming these variables? or is there some reason they have names like we and w that don't appear to actually mean anything?
uh well i was lazy and im just testing my skills
coding skills including making your code readable
try logging some useful information, like digi suggested instead of just logging the word "moving" since that doesn't actually tell you anything
I don't see any movement happening at all in that example
nvm i think its because i forgot to make speed higher and rigidbody not get effectedby objects changing it rotation
i mean freese rotation
When I hit the Space button, why does my word get deleted?
press the insert key on your keyboard
it toggles the input mode between insert and replace
also configure your ide
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
âą
Visual Studio (Installed via Unity Hub)
âą
Visual Studio (Installed manually)
âą
VS Code
âą
JetBrains Rider
âą :question: Other/None
oh thank you
{
public Produce product;
public GameObject screen;
}
public class SupplyPurchaser : MonoBehaviour
{
public Storage produceHandler;
public GameObject listingPrefab;
public GameObject scrollView;
public void Start()
{
Initialize();
}
private void Initialize()
{
Listing[] listing = new Listing[produceHandler.produce.Length - 1];
for (int i = 0; i < produceHandler.produce.Length; i++)
{
Debug.Log(i);
listing[i].product = produceHandler.produce[i];
listing[i].screen = Instantiate(listingPrefab, scrollView.transform);
listing[i].screen.name = listing[i].product.itemName;
listing[i].screen.GetComponent<PurchaseAmountHandler>().Initialize(listing[i].product);
}
}
}```
according to unity, line 34 `listing[i].product = produceHandler.produce[i];` has the following error: Object reference not set to an instance of an object
i imagine im just not understanding how classes work, this is my first time really messing with them
aplogies if this isn't exactly the right channel for this - I'm looking to do something adjacent to A* pathfinding for my game. However, I can't really find a tutorial which covers pathfinding for a non-grid based non-top-down scenario. all I need really is a way for each of these green rectangles the know who their neighbouring rectangles are so they know how to calculate a path towards a destination, e.g. the character is at the red star, and now needs to go to the red cross. Is there an obvious way of setting up a "web" or these neighbouring boxes/grids/waypoints etc? considering the fact that some areas will be more complex and forking than this one
the first thing I thought of when it came to implementing this was to actually create invisible rectangle gameobjectthat do overlap physically, so they can check for a physics overlap to know where their neighbours are when a new path is being looked for, but that sounds kinda resource intensive?
tl;dr, best way to make a custom grid where each component knows what's neighbouring it?
You arent creating instances of Listing, yet are trying to access the .product of a listing. You've created the list but not the elements inside
Either listing, listing[i], produceHandler, or produceHandler.produce is null
Is this a good tiling script using UnityEngine;
[ExecuteInEditMode]
public class IndividualSideTiler : MonoBehaviour
{
[System.Serializable]
public struct SideSettings
{
public Vector2 tiling;
public Vector2 offset;
}
public SideSettings top = new SideSettings { tiling = new Vector2(1, 1) };
public SideSettings bottom = new SideSettings { tiling = new Vector2(1, 1) };
public SideSettings front = new SideSettings { tiling = new Vector2(1, 1) };
public SideSettings back = new SideSettings { tiling = new Vector2(1, 1) };
public SideSettings left = new SideSettings { tiling = new Vector2(1, 1) };
public SideSettings right = new SideSettings { tiling = new Vector2(1, 1) };
private MeshFilter meshFilter;
private Mesh originalMesh;
private Vector2[] baseUVs;
void OnEnable()
{
meshFilter = GetComponent<MeshFilter>();
if (meshFilter != null && meshFilter.sharedMesh != null)
{
// Store the original mesh UVs so we don't "stack" tiling every frame
originalMesh = meshFilter.sharedMesh;
baseUVs = originalMesh.uv;
}
}
void Update()
{
if (meshFilter == null || baseUVs == null) return;
ApplyCustomUVs();
}
void ApplyCustomUVs()
{
Vector3[] normals = originalMesh.normals;
Vector2[] newUVs = new Vector2[baseUVs.Length];
for (int i = 0; i < newUVs.Length; i++)
{
Vector3 n = normals[i];
SideSettings settings = front;
// Logic to find which side is which based on direction
if (Mathf.Abs(n.y) > 0.5f) settings = n.y > 0 ? top : bottom;
else if (Mathf.Abs(n.x) > 0.5f) settings = n.x > 0 ? right : left;
else if (Mathf.Abs(n.z) > 0.5f) settings = n.z > 0 ? front : back;
newUVs[i] = new Vector2(
baseUVs[i].x * settings.tiling.x + settings.offset.x,
baseUVs[i].y * settings.tiling.y + settings.offset.y
);
}
// Apply the modified UVs to a unique instance of the mesh
meshFilter.mesh.uv = newUVs;
}
}
Eh why is that link in here? đ
Does anyone know how I can fix this error? I can't seem to find this option in the inspector
its called Read/Write
I found it thx
Ok now instantiating the object itself doesn't seem to work
I've tested that this runs but no object gets instantiated
make sure it isn't actually being destroyed immediately because this will instantiate the object
also, I know it isn't a compile error because there's the implicit cast and it will make no difference here, but you probably want to be using UnityEngine.Quaternion rather than Unity.Mathematics.quaternion unless you actually know why you would want to be using the latter rather than the former
Why are you subtracting 1 from Length when you sample Random?
It's zero based right?
If there were only 1 object and I rolled a 1 wouldn't that be outside of the array?
But yeah I got the thing to work
yes, but Random.Range with ints is max exclusive so it can never return the second number
character controller:
!code but also if the error is only in the unity console that means you haven't saved this code
đ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
đ 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.
logic manager:
ok, it lets me run the game now, but i can still flap after death and this error appears:
and what is line 27 of Logic.cs
then bee is not assigned, make sure you've dragged the reference into the inspector since that variable is serialized
ok
there's no error message now, but it still dosn't work, im guessing i have to specify the object and then the script attached to it?
you likely have more than one Logic component in the scene and the other one, which is the one being found with that FindGameObjectWithTag call, doesn't have it assigned. you should do two things here:
- remove extra Logic components if you only need the one
- serialize your logic variable and drag the reference in like you've done for these other variables instead of relying on a GameObject.FindXXX call
would something like this work?
colliders having the same layer will def collide with each other
its just this
that doesn't change what i said. search the hierarchy using t:Logic and you'll see at least two Logic components in the scene
this is my code for my monsterAI
!code
đ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
đ 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.
okay now look at your Update method. what if statement do you think is being entered with this as your layermask
should i put player and ground to default?
they should be whatever layer the objects you are trying to detect are on
what do you mean by this?
it's a dropdown menu that will open up to list all of the layers
yes, those are all of the existing layers that you have
look at the object(s) you want to detect and look at what layer you've put them on
ideally you'd create a new layer specifically for the player and put it on that layer, then only include that layer for your "what is player" layermask
same for ground, really (although this isn't a strict requirement like the above would be)
and you definitely do not want those things on the same layer, otherwise you'll be detecting the ground as the player
how do i make this work? do i say 'if (Collision2D.tag == ("Pipe")' instead?
use the compare tag method, not string equality. but also you need to get the tag of the collider/gameObject that is being collided with which the Collision2D object has a reference to
you were so close before when you posted in the wrong channel, you just weren't using the correct method name
how would i write that
go back to the code you had before and change it to the correct method name
i made 2 layers for player and monster, but it's still not moving 
Do i need a layer for monster aswell maybe?
what layer is the ground on
i mean the actual object in the scene, not the layermask variable
right, so if the ground is on the Ground layer, and you are detecting the player by checking if anything is within range on the Ground layer, which of the three if statements in your Update method do you think is currently true?
This looks fine. If using a trigger or collision check, remember to compare the layers
When using the Overlap or Cast methods, use the layer as a filter . . .
why would i want to compare the layers? can't i just use the layer collision matrix to decide which layers should be colliding?
hey can someone PLEASE HELP ME ive been on the internet for about some time now about 3 months looking for SOMETHING to help me learn C# and the fact is, theres so much i dont know where to put my time to learn. I was watching sebatian Leauge videos but he goes a bit fast and often i rewatch videos and feel stupid. My name is SirSurf and if anyone can help a beginner that would help. I want to create games in Unity and learn how to do C# so i can later do it as a game dev in the future and this is something that i really want to spend time on so if someone could give me a course because thats what i was looking for before and it was alright and so did videos and i came here to also ask questions about things.... yeah... sorry for the rant.....
there are beginner c# courses pinned in this channel
i feel so lost
do a beginner c# course
and start coding, not just watching videos
Only if you use the Cast or Overlap methods bc you can provide a layer(s) as a filter . . .
can you reccomend somthing?
check out the pins as @slender nymph suggested
@tired python Placing GameObjects on a layer does not automatically filter them during collisions . . .
CompareTag dosen't exist??
yes it does (provided you call it on the correct type of object)
i call it on 'collider' right?
i think there might be a miscommunication going on, cus i checked this out, and well, the Tower layer does collide with the Enemies layer
maybe you are thinking of a specific scenario or something? i don't quite get it
yes, you can call CompareTag on a Collider2D. show your actual code
If you use trigger or collision methods, comparing layers is the fastest option, TryGetComponent is slower (but still fast) and gives you the component of the object has one . . .
can all fundementals of C# be applied in other things? a problem i find is how to use code creativly but i dont think you guys are like a dictionary or google so if you cant answer that its fine
several things wrong here, for one, this isn't even attempting to use CompareTag. for two, you are doing this on a Collision2D not a Collider2D. those are different types of objects
Collision2D does not have a tag property . . .
yea that was the old code
yes it does. it's Collision2D that doesn't
And you didn't even use CompareTag . . .
collision.gameObject.tag i think like in this
now go back to the even older code where you asked what you did wrong and it was pointed out you had the wrong method name. then just use the right method name
which is exactly what i already told you to do but you just didn't for some reason
You're just adding things randomly now. You need to access a field or property that has the CompareTag method . . .
What do you mean by "other things? "
why would i need to compare layers, can't i just set the right layers for the right colliders just as is, i don't find the need to compare layers, i just make the child objects and main objects have the right layers from the get go
is there an easy way to check for both collision and trigger enter?
in the same statement
Yes, because you checked them to collide. I'm not sure why nothing else is checked, though. These are the collisions for all of your objects. Currently, only those two layers will collide with each other; nothing else . . .
depends on the use case. if you are referring to the OnTriggerEnter and OnCollisionEnter methods though, those are separate methods.
ya, i don't need most of those checked, i am experimenting still
what i mean is can i check for both simultaniously
if your logic is exactly the same in both of them you could just have each of them call the same method though (passing relevant data like the collider entered/collided with)
not those methods, no. because, again, they are separate methods. you could use physics queries to check for overlapping colliders and do manual collision checking, but that's a lot of work and the right thing to do depends entirely on what you are actually trying to accomplish
you know what, i will implement what i am tryna do, and then post it to you later, @cosmic dagger
@tired python No, the layer matrix only determines what objects can collide with each other. Any GameObject with a collider will trigger a collision on another GameObject with a trigger or collision method . . .
given that both of them have the box in common checked out in the layer matrix
You need a filter to find out if the collided GameObject is the one you are looking for. There are multiple ways to filter . . .
- compare layers
- check Component
- compare tags
Anytime you have a collision, whether using a trigger/collision method, the Cast methods, or the Overlap methods, you need a filter to check the collided object(s) . . .
suppose i have two different GameObjects one of which has a kinematic collider, while the other one has a static collider. If i were to rb.useFullKinematicContacts = true; on the GameObject having the static collider, would it recognise collisions with the GameObject having the kinematic collider?
cus on trying it out, i am having to enable the Use Full Kinematic Collision on the GameObject having the Kinematic collider, and only then is the collision being detected...
said GameObjects in question
Have you read this?
I think it explains it all pretty clearly: https://docs.unity3d.com/ScriptReference/Rigidbody2D-useFullKinematicContacts.html
correct. without that setting Kinematic bodies do not collide with static colliders
https://unity.huh.how/physics-messages/collision-matrix-2d
This is only used when the bodyType is set to RigidbodyType2D.Kinematic.
no like i get that, but the setup i had before was one in which both the GameObjects had Kinematic and Static on them, and just having a script attached to the GameObject having the Static rigidbody2D, which had this line rb.useFullKinematicContacts = true; would make them collide with each other
I doubt that, because as the docs say, that property doesn't do anything unless the body is kinematic
are you certain that wasn't setting it on the kinematic body?
oh ya, i do remember changing it to static once i found out that static is used for GameObjects which don't move.
and it stopped working after that
is there even a specific reason this object has a rigidbody on it if you want it to be static anyway? i get that under very specific circumstances that would be necessary, but it doesn't seem like it is here
ya, remember the dragon trashcan? it detects when a unit is put on its collider and blasts it away
what does that have to do with having a static rigidbody?
right, which is why i'm asking why it has a rigidbody at all
cus collision checks can't happen with just a collider
making the rigidbody static is exactly the same as having no rigidbody when it comes to collision detection
đ
wait, so a GameObject with just a collider in it which is static triggers OnCollisionEnter2D?
no, only a dynamic rigidbody will cause those messages
I mean, static body is just one without rigidbody
oh, well in that case, the dragon does need the rb cus it has a script attached to it which checks for collision and blasts it away
right, but for 2d there is the Static body type which functions exactly the same as having no rigidbody (but with the added benefit of creating the compound collider)
but it doesn't need the rigidbody here because the rigidbody is static. the other object is what is causing the OnCollision message to be sent to this object
well, i don't want the other GameObject's script to have more lines of code
nobody said that was necessary. all i'm saying is that the static rigidbody on this object is doing literally nothing at all and can be removed
WAIT A SEC
and object can still receive a collision message from a dynamic rigidbody even if it doesn't have one itself. it's only the dynamic rigidbody that is actually sending that message
that's srsly trippy
the other gameobject sends the msg to the static gameobject
that is how physics messages work, yes
If u are talking about trigger, static can still receive it
not talking about trigger
that is not in question here. and is, in fact, pretty much what i have been saying this entire time. the dynamic rigidbody is sending the collision message to the static collider
or i guess maybe it's a kinematic body with full contacts enabled. either way though, the non-static body is sending the message to both objects
what if i were to attach the same mechanism to the different scripts, as in, destroy the gameobject, would one destroy the gameobject and then the other return an nre?
naw
aight
oh wait, nvm, it won't work, cus i am already using a collision check to do something else, i would need to check for layer in that case i guess
how would i teleport an object to say, 0 -10 0?
assign its transform.position to that
something like this?
you should do some beginner c# courses to learn how the language works. there are some excellent ones pinned in this channel
although if you are doing this for a rigidbody you'd want to set the rigidbody.position rather than the transform's position
you should still go through some beginner c# courses to actually learn how the language works instead of just guessing though
ok, i will
tysm
@slender nymph it does return a nre
show exactly where you are getting this NullReferenceException, because a destroyed object doesn't actually become null. so you'd be getting a different error if you were trying to operate on a destroyed object.
static GameObject
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "UIDroplet")
{
Debug.Log("Muahaha");
Destroy(gameObject);
}
}```
`Kinematic GameObject`
i am getting the error in the highlighted portion
and what is the actual error you receive
NullReferenceException: Object reference not set to an instance of an object
also you don't need a coroutine to delay Destroy, it has a second paramter for the delay
i know that, i just wanted to try implementing it for the first time
but . . . why? if you know it isn't necessary and that the Destroy call already accounts for a delay, why would you create a coroutine for a delay?
anyway, the NRE is actually likely being caused by the fact that unity will reuse those Collision2D objects
Can you show us the actual full error message you are seeing in the console window?
NullReferenceException: Object reference not set to an instance of an object
UnityEngine.Collision2D.get_gameObject () (at <f1a2e4fe3e024bda9959a5de412d1a5e>:0)
ColliderCollisionCheckScript+<DestroyAfterTime>d__2.MoveNext () (at Assets/Scripts/Collision/ToothlessCollision/ToothlessCollision.cs:28)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <a25ed31d46d841d0bef9ea31576356a5>:0)
this is 28
yeah the NRE is inside the gameObject property getter on the Collision2D object - box is dead-on about this being an issue of tryin gto use Collision2D this way
why don't you just pass the GameObject as the parameter
Collision2D isn't something you should hold onto for a long time
elaborate
likely that Collision2D has been returned the Unity's internal object pool and cleared
elaborate on the proposed solution?
Change to this:
StartCoroutine(DestroyAfterTime(col.gameObject));
and just fix up the DestroyAfterTime coroutine to operate on a GameObject param instead of a Collision2D
Start the routine with the game objectcs StartCoroutine(whatever.gameObject);Image provided, so I did not bother copying exactly as is.
Where you'd change the definition of the ienumerator function to take a game object instead
https://docs.unity3d.com/Manual/class-Physics2DSettings.html
it is reusing the same instance of the Collision2D for every Collision message so it sets the gameObject (and others) propery to null.
you need to pass the GameObject directly to your coroutine not the Collision2D to avoid this
no, as in, what you meant when you said gameObject is a property of whatever col is and that nre is a problem or smth
You have a reference to a Collision2D obejct and you're accessing the .gameObject property on it. The NRE is coming from the property getter, as you can see in your stack trace
we don't know the source code for the property getter so we can't tell exactly what the issue is but basically you can't assume that Collision2D object will be valid in 1.5 seconds. It;s only guaranteed to be valid right inside OnCollisionEnter2D
not the actual obj?
The collision 2d that you receive on collision is being reused by the system internally so it's game object property is set to null after the message event?
it's a class so it's a reference to the same object
nope, Collision2D is a class - so you have a reference to it, not a copy.
ok
wait let me digest
something like this?
both of them are different pointers pointing to the same address?
yes. that's how reference types work
except they aren't really pointers because that's not a thing you work with in c# (with the exception of unsafe code)
if the gameobject = null it returns a nre?
no, something inside the property getter for the Collision2D's .gameObject property is throwing an NRE.
it's closed source so we don't know exactly what the root cause is.
there are pointers in c# though right?
only in unsafe code, yes. references are similar but not quite the same thing
ya, i won't delve into that, i just figured out pointers a couple weeks ago, don't wanna mess up my understanding without having gained a safe enough intuition for pointers
i dont think under normal circumstances u get to use it tho
i do a bit of cpp too, that's why...
C++ also uses references.. C would be a different story.
aren't pointers basically variables which store addresses?
Right but no one (higher level languages) uses them anymore unless they've got to.
C# and C++ is very very different
Safety generally precedes performance. C++ would have you opt for smart pointers rather than raw pointers
u cant treat C# and the workflow same as C++
i don't know nearly enough to even begin to comprehend why that is so, but aight
ok, now the nre is not appearing
I think pointers are useful when you want to handle memory yourself, so with static vs dynamic behaviors
in C# I don't think it's a thing just cuz uhh, well I don't know, I only used pointers for school making weird memory sections
can you maybe give an example as to why it would be problematic to hold?
was the error you were just getting not enough of an example?
I believe they've informed you that the state is constantly changing
This entire discussion has been the example
your error, mainly
ya, it does not produce that error anymore
because you're passing the gameobject around now, not the Collision2D
the gameobject was not the problem, it was the Collision2D and whatever it is doing in the property getters
In programming, we're meant to avoid undefined behavior. Having access to some data that's not guaranteed to be what we think it is after our use case is pretty undefined.
last question, is there an instance where i would want to use a static collider with a rigidbody2D attached to the same GameObject?
the irony is that i predicted that it would be an nre xD
can you be more specific about what precisely you are referring to? because that's a pretty normal workflow (assuming by "static collider" you are referring to just a collider because colliders themselves are not static or dynamic)
but you predicted it about a different unrelated reason
this had absolutely nothing to do with destroying the object
when and how do people normally use static rigidbodie with collidersattached to them. because you mentioned something along the lines of, what I was doing could have been implemented without using the rigidbody component attached to the GameObject. That gave me a hint as to there might be a situation where you would want to attach a rb to the GameObject. Does that make sense?
you are getting your terminology backwards. it was a static rigidbody. the collider is always static because it is not what controls whether it is dynamic, that's the rigidbody.
oh sorry
and you almost never need to use a static rigidbody unless you need to create a compound collider (basically treat all child colliders as one big collider) for an object that should never be affected by physics or move
I think of static colliders as walls or immovable objects. They aren't meant to move.
I think of objects with rigid bodies as objects that should move.
Both would require colliders of some kind.
a static rigidbody probably also receives the collision/trigger messages that are sent to child colliders so could probably be useful to make sure those messages are received by a root object
although it does appear that all collider2ds in the scene that don't have an attached rigidbody are all considered attached to the same static rigidbody so if you end up needing to move specific colliders that aren't part of a dynamic or kinematic rigidbody then you should put a static rigidbody on them because it's faster to move that way
another thing, i have kind of gotten the hang of how to use the Scripting API, but i don't know what the manual is used for
as you can see from the manual link i provided, the manual is meant to give information about different concepts
Scripting API is coding-specific, Manual is all the other stuff
Some like Addressables are not included in Scripting, so u have to look into Manual
Do you guys use ScriptableObjects over Singletons?
We can use pointers when working with unsafe code in c#. We cant have pointers to managed objects safely because they can be relocated at anytime (by the .NET runtime)
There are extra keywords we can use to prevent object relocation but thats getting to off topic for a beginner channel. TLDR we dont use pointers in normal c#
over? not really. What's an example?
I've sometimes used some singleton-esque scriptableobject stuff in order to reference my content collections accessible statically
these are two separate ideas!
ctrl + z
this is a code channel, that is not a code question.
just rmb -> add a camera -> set the tag as main camera
oh sorry im just really new in unity TT
It's ok to be new, but, being new to unity doesn't mean you're new to reading and understanding what channel names mean, or mean you can't read channel topics.
my anmation keep geting stuck with each other they like turning to jump to attack to jump to attack and so on how do i fix it? heres movement code https://paste.mod.gg/inhzvxwbljsh/0 (from attack to idle there is no issue)
A tool for sharing your source code with the world!
use blend tree
what blend tree is?
Simply put, it's something that organizes animations in the Animator when there are a number of animations that are somewhat similar to each other, like running without a weapon, running without a weapon, and light running. You can organize them all in the blend tree. I recommend looking it up.
ok i will do you think it will fix my problem?
i don't see how a blend tree would help here
if you're flapping between two states, that means that there are valid transitions in both directions
so if it's flipping between "Jump" and "Attack", look at the transitions between those states
is it possible for both to be valid at the same time?
no cuse for it to move for jump or run its need attack to be worng and for it to go to attack its need to be right
show the conditions for the "Jump" -> "Attack" transition
i did
here
oh i didnt
wait
no, you showed the "Run" ->" Attack" transition
I'm not sure, but generally I don't speak English, so there might be a slight misunderstanding.
idk you got a good english
now i did
really ?
yeah bro look at it not even one typo
I understand a little, but I'm better at writing than reading.
what about that "Any State" transition?
i didnt use it i have to?
note that this transition does not care if you're attacking
these transitions are legal at the same time:
Any State -> jump
jump -> attack
I'm starting to understand a little. I've had many problems like this with the animator, so I've been working with animation using code.
thank you i tried a lot of time and it didnt work i appricate you
what?
Any State can be tricky to deal with, since it really does allow transitions from any state
Hello, I'm a complete beginner with Unity. I'm trying to work on a project, but unfortunately, I'm stuck on shaders and materials. The problem isn't so much the code itself, but Unity's logic. If someone could come and help me in pm, I would be very grateful. (I don't think I'm that far from figuring it out.)
Sounds like a #1390346776804069396 question, not code. Feel free to share the details of your problem in that channel, that'll be the best way to get help.
okay, thanks
Hello, what's the best way to make switching between splinecontainers smooth? I asked ChatGPT, this is what I got.
public IEnumerator SmoothSwitch(SplineContainer oldSc, SplineContainer newSc, bool front, float targetT)
{
Transform bogie = front ? frontBogie : rearBogie;
float currentT = front ? t : rearT;
Vector3 startPos = oldSc.EvaluatePosition(0, currentT);
Vector3 startTan = oldSc.EvaluateTangent(0, currentT);
// approximate distance along old spline to switch
float switchDistance = Vector3.Distance(startPos, newSc.EvaluatePosition(0, targetT));
float speed = Mathf.Max(0.01f, Mathf.Abs(tData.currentSpeed));
float elapsed = 0f;
float duration = switchDistance / speed;
while (elapsed < duration)
{
elapsed += Time.deltaTime;
float blend = Mathf.Clamp01(elapsed / duration);
// pretend moving along old spline
float simulatedT = Mathf.Lerp(currentT,1, blend);
bogie.position = oldSc.EvaluatePosition(0, simulatedT);
Vector3 tan = oldSc.EvaluateTangent(0, simulatedT);
if (tan != Vector3.zero)
bogie.right = tan;
yield return null;
}
// snap to new spline
bogie.position = newSc.EvaluatePosition(0, targetT);
bogie.right = newSc.EvaluateTangent(0, targetT);
if (front)
{
t = targetT;
frontSc = newSc;
}
else
{
rearT = targetT;
rearSc = newSc;
}
}```
it kinda works, but its not real smooth.
are the values of x and y in a Vector 2 object always -1,0 or 1 ?
no, what makes you think that
float, float, float.. can be any float
some apis, or some contexts, might only give those values, but that's a rule of that api, not of Vector2 in general
Vector2 is just 2 floats
a 2d vector
oh (2) yeap.. float float
whenever I print the .x and .y i always see -1,0 or 1 depending on if im pressing a key so I thought it would only take on those
that's a rule of the thing you're reading the Vector2 from, not of Vector2 itself
consider what would happen if your keyboard were analog or if that input were hooked up to a controller's joystick
oh like the triggers on controllers ?
sure, those are usually analog iirc
for axis inputs, the result is often "normalized", in the range 0 to 1
when it's from digital hardware, you get 0 or 1 - no in between values, that's what digital means
-# footnote: there are 2 meanings for normalized, the other applies to entire structs - a normalized Vector2 has a magnitude of 1, etc
how can i access that web where i can type my code and send it here ?
!code
đ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
đ 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.
use an external paste bin ^ or codeblocks if its short enough
thanks bud
I would just evaluate the position for both splines at T and interpolate between them.
alright thanks
Is Time.DeltaTime in seconds?
YES
it also helps to think of deltatime in seconds per frame (or per step, per tick etc as you generalize it)
this is an annoying one
I've seen it when my objects go flying violently out of bounds
there's no stack trace because the error only shows up when Unity tries to figure out the position of something on the screen
you don't get to see the moment where it went wrong
hey does anyone have any solid courses for C# beginner because well im not a kid and when i tried the ones on the front page they didnt really make me feel like I was learning to use C# creativly for games. If someone could help that would be great!
well if you need a begineer tutorial for c# then its not exactly going to anything flashy or even related to game development that much
you should probably get a basic understanding of the syntax and language before you start applying it in unity
there are beginner resources pinned in this channel
one link is dead
yea idk it feels a lil confusing
lowkey might not even bother with coding since im not smart enough ykđ
well if you want to make games you have to learn coding regardless of how smart you are
ik but i have a learning disorder so things overwhelm me quickly and i dont know where to start. its easy for you as a seasoned dev to say " oh just start" when i dont know where to put my time because i feel like it will take me 10+ years to understand the basics and by the time i have that then i wont even want to do what i wanted to do...
coding kinda does that regardless of any learning disorders
it's hard to a degree, but it looks way harder than it is
maybe thisll help
(in general) there's 3 major parts to programming:
- Language - The syntax, structure, and paradigm of each language
- Library - The interfaces and utilities that each environment or toolset provides
- Logic - The algorithms to do work at runtime
Logic is almost completely transferrable between each language and environment, you just have to learn the specific Language and Library that you're using
Language is also shared quite a bit between languagesof course, learning 1 part at a time is easier than learning everything at once, which is why tools like scratch or code.org are popular as coding courses for beginners, especially kids, because it only focuses on the Logic aspect
"a seasoned dev"
im seasoned with salt
im still a beginner all things considered lol and im still learning myself
i also dont know why you would quote "oh just start" when neither I or anybody else here said that, we even showed you explicitly what to start with
Anyways coding at its fundamental level is about problem solving in bite sized chunks, there are thousands of free resources online where you can start doing this
if you have some previous experience coding then thats great, it means adapting to c# should be really fast, but if not you should start with something more lowkey and not unity
code.org in particular is great
how should I go about instantiating and assigning a bunch of different materials onto my prefab?
I have a setup to edit colours, where it uses sharedMaterial so it affects all of the prefabs gameObjects that use the material, but I can't do that if I want multiple instances of the prefab, otherwise it'll affect all of them.
so I'm looking for a solid solution to make it so each prefab has it's own set of materials that I'll be manipulating through code (that would affect all gameobjects using each specific material)
and I know I could just make a list of gameobjects for each material type and then iterate through them but that sounds super clunky and kind of overkill
Usually that's the idea, yeah
oh, alright lol
it sounded pretty hacky but if that's what the norm is then I guess I'll roll with it
You can however lessen the iteration if say you want a single variable to modify all instances, meaning you do want to keep some shared parameters between instancing and you can usually do that with global shader parameters
yeah I was hoping for a single variable to change the param in the shader, I just need it to affect all the gameobjects using that material, within the prefab
I was just gonna instantiate the materials, iterate through all gameobjects that I have in lists, assign the newly instantiated material, then edit that materials shader params the same way I initially did
it just seems very overengineered when it initially was just "edit sharedmaterial shader params"
https://docs.unity3d.com/6000.3/Documentation/Manual/materialvariant-concept.html
You do have these, but more of an editor time concept. I'm actually not entirely sure if that can extend to the runtime but not something I've looked into.
hmm I'll look into those, thank you
i believe you can just access the materials property of the prefab's Renderer, which will cause all of the materials to be instantiated
I'm not sure what consequences that'd have in the editor, though
oh, wait, you're talking about making each instance of the prefab unique
not making each prefab's material distinct from other prefabs' materials
I can't edit the shader parameters if I did that though
otherwise it'd edit it for every prefab that uses those materials
you should either:
- access
Renderer.materialsand then mess with those materials (which will be made unique to the renderer) - use MaterialPropertyBlock to set specific properties on a specific renderer
access Renderer.materials and then mess with those materials (which will be made unique to the renderer)
this would only edit a single gameobject that uses that material though, which is the main issue I'm running into
ah, all uses of the material within a single prefab instance
yeah
that's the important part I missed
like skin tone, hair colour, etc etc
since you can swap parts out, there are a bunch of seperated parts per prefab
Can i get some assistance with like super basic code? ive been trying to test out this line for like a week and ive went through a bunch of updates and dowloads and it looks like it would work but has two errors that idk how to fix
i dont see any code
i didnt send it, i meant if i could vc with someone sometime about it
nope
You should open with your actual question/intention, instead of baiting a response.
We don't have VC in this server. Ask your question, show the code, and people can help if they can.
If it's "super basic" and a "line" , then there's no reason it needs to be a complex issue.
Missing semicolon on line 14
bro wdym lmao
well its not like one line but yknow
Given there's zero information to anyone to actually give a useful solution I figured I'd just give a solution without a question.
One of these days it's actually going to be a semicolon on line 14 and then I can retire
math
Why does my brand new Unity project have compiler errors from an invisible package
Try restarting Unity
Other than that, they look like collab and version control configuration issues
I tried restarting Unity, deleting and rebuilding a project, and clearing my cache. I ended up having to remove "com.unity.collab-proxy" from my manifest entirely and it worked
can i slice multiple images at once ?
I recommend to Learn with ChatGPT Model 5. it help me Very much. But First, try to learn a Little Bit c# and then with unity. U dont have to know much c#. only how u Write it.
We donât recommend AI for beginners
I'm not sure what is wrong with my player that is not moving
I have the new input system and I copied the tutorials source code :D
Learn how to build a 2D platformer with Unity's new input system!
Source code: https://gist.github.com/bendux/a660a720c73dbeb4b4eff5f2dd43167b
SOCIAL
Discord: https://discord.gg/harSKuFR8U
itch.io: https://bendux.itch.io/
Twitter: https://twitter.com/bendux_studios
SUPPORT
Buy Me a Coffee: https://www.buymeacoffee.com/bendux
MUSIC
Marc...
Okay nevermind
I think I should continue the another tutorial i'm doing
the main game
v += Physics.gravity * stepTime;//stepTime = 0.05f, v is vector 3
pos += v * stepTime;//stepTime = 0.05f, v = vector3, grenade pos = pos here
bro what does this means ? i cant understand why and how it is done and what its work
https://paste.mod.gg/eelrfqgkjytj/0 here
A tool for sharing your source code with the world!
explain it please why it has done ?
where is the code from?
its a script of grenade throwing mechanism
it is showing the trajectory of the grenade
where is the code from?
AI
why dont you ask the AI then
GUys tell me how can i start using maths in my code ? how can i learn using formulas in my code
i think you should learn the c# basics first
it sounds like you are using ai code too much and you donÂŽt know what the code does
i know basics but i dont know to use mathematics in unity cuz it is much different that i do in my note book
Seems like u are having trouble understanding the operators
no , not with operators but mathf and all, because i can do it on my paper but not able to do it in my script
It's hard to explain unless u provide more context. Perhaps the full script with the actual implementation of ur function.
And the formula u are trying to implement as well. I think it's best to create a thread in #1390346827005431951 for this type of question.
!vscode
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
Are scriptable objects a good way of doing eventa to keep everything modular?
can anyone help me with a script?
You can try but you need to ensure the same instance remains loaded and used
is it tricky or pretty straight forward?
Its not hard but you are moving the location of the event for little or no benefit
because the main problem i have now is since i do multiplayer i cannot have multiple statics of some classes as that would cause alot of problems
then have the events not be static?
yes but then they will need a reference
If the issue is getting a reference to the object then you just need to improve how you initialize and share dependencies
i want to decouple my scripts more
U can just say what the problem is
You can only do that soo much. Things need to depend on what they need to function
anyway i cant comment more when I dont know specifics
There are specific design pattern for this purpose. MVC/MVP, factory pattern, etc.
for example say i got a main player controller then i have a script thats like the base mechanics of the game,in order for them to talk to each other i will need to do get component on awake to get references to each script since they rely on each other
Yes, or whatever spawns the player can get a reference then and also initialize the player
e.g. spawn player, init player with player data
You dont have to only stick with Awake/Start...
DI frameworks exist for this reason, they essentially automate the initialisation of objects with dependencies
Hmmm never used dependancy injection before
I would not recommend that just yet
I'm working inside a namespace but I need access to an abstract class from outside of it in my normal project, how do I do that?
Canât u just inherit it like u normally do? Namespace does not restrict access of classes
I can't no, it does restrict access
Show the abstract class
What is the error it's showing?
I think I figured it out xD it's probably the assembly definition stuff, I don't fully understand it
nvm it's not working, I don't get namespaces Dx
Idk why u need that namespace. It does not seem to be a standard. U probably can just get rid of that altogether
it deals with the graph toolkit package which doesn't work nicely without assembly definitions
I'm not sure I get your point
u can access a class from a different script
I'm using a namespace and assembly definition
but I can't get the assembly definition to accept my class from outside of it
oh
Ok, what is the exact error it's reporting?
well it just doesn't know it's a class
i checked if there were any references and there are non so i don't think that exists on unity
i could be wrong tho
that is the issue yes, I don't think you understand the problem.
the EventSystem object that gets created whenever I have UI elements has this property:
How do I access this through code?
The only explanation i could find online was https://docs.unity3d.com/6000.2/Documentation/Manual/UIE-Navigation-Events.html
which is no longer supported
The editor version isn't supported. It doesn't mean the navigation event. https://docs.unity3d.com/Manual/UIE-Navigation-Events.html
Hm, do u have another Assembly Definition inside the same folder of ScriptableData
This could mean a numerous of things, but since u mention assembly, I have to ask
nope
Well that's certainly part of the problem. You should read about how assembly definitions work
https://docs.unity3d.com/6000.3/Documentation/Manual/assembly-definition-files.html
Yeah, I'm not familiar with this either so I did some experiment.
If the scripts are in different folders with their own .asmdef, u either have to include them in the same assembly folder, or create new assembly for each folder and reference them in each other.
yea I read some of the docs and I gave the AEData namespace an assembly definition and added it to the references of the other one.
does this mean that you need an assembly definition to reference classes in other assembly definitions? or is this just the easiest way to do it?
Yes, as the docs say custom assemblies (like those created with assembly definitions) can't reference the predefined ones (like Assembly-CSharp)
I guess that did fix the errors so far, thanks for the info. the more you know I guess 
is it just me or do some assets not show the material instead show a pink colour, if its just me how do i fix it
this is a code channel.
but also https://unity.huh.how/shaders/errors
quick question, i want to update my âline drawingâ code from instantiating circles while the mouse is held down (super intensive, looks like shit and i cant find a decent tutorial to interpolate it so theyre super spread out) into a line renderer or any other kind of line drawing substitute. however, ive got other pieces of code that check how many circles have been spawned inside of a hitbox to tell if youve âdrawnâ inside of that hitbox for long enough and then run the rest of their code, would switching to a line renderer make this impossible (or at the very least alot harder) since im assuming itll all be treated as one hitbox and not many multiple ones?
If you want a straight port, you could technically use circles abstractly but instead of being actual circles with colliders they simply are the points that make up the line renderer.
As for tracking within an area, you can count the points inside of an area (there's probably papers online to determine if a point inside a shape). Or go the easy route and iterate through each point and do an overlapcircle call to check for collision on the hitbox and count them up.
you may be underestimating how much of a beginner i am i hardly comprehend a thing you just said
but at least i know there are ways
Well, that's the extent I can go with mobile.
