#archived-code-general
1 messages · Page 237 of 1
I'm just a freshman in university. 
how I feel right about now but atleast making a 2d game was hella fun
We didn't have coding lessons in high school, I did media arts tho.
even if it sucked!
uh hi could someone help me understand gameobjects activation and like when methods are called or not
I have some very simple code which just prints a gameobject's activeSelf value before and after calling SetActive and its false both times
Debug.Log($"{gameObject.name} is active: {gameObject.activeSelf}");
gameObject.SetActive(true);
Debug.Log($"{gameObject.name} is active: {gameObject.activeSelf}");
which yields the following log
some things online have led me to believe that maybe a script cant activate the gameobject that its on? but that is what I have been doing this whole time
the only thing that has changed is that now this object is late initialized, like i moved the initialization code from Start to OnEnable and then it starts out disabled and gets enabled later
to me, the specifics of when functions will be called is all magic
initialization order for one, but in this case its what gets called when a behavior is enabled and a gameobject activated
according to the inspector, this is an enabled script trying to call SetActive(true) on its inactive game object, which should work in my head
this should work fine
possibly some other script has an OnEnable that deactivates the object or something?
Or perhaps an exception is being thrown in some object's Awake?
Try https://docs.unity3d.com/ScriptReference/GameObject-activeInHierarchy.html if you've got an inactive parent.
activeSelf I would expect to work properly here no matter what the parents are doing
the script is on the root object which is disabled, none of the parents are disabled
can you show the rest of your console window?
sure
Update and whatnot are not called from inactive objects / disabled components.
Surely you're calling this function from another script 
Or when the object isn't inactive or component isn't disabled.
indeed i am
heres the first thing, this is just the inspector and the hierarchy before starting the game
the thing i put a blue rectangle around is the script calling SetActive
Ok actually I have a theory here now - I think you're trying to call SetActive on a prefab.
object deactivates itself and the component enables itself
isnt it all gameobject once instantiated?
sure, as long as you call the function on the instance not the prefab
i thought prefabs were just an editor concept
prefabs are not just an editor concept
prefabs are GameObjects that exist in memory but not in the scene
Where are you referencing this component?
Yes - how and where are you referencing the script and calling the function from?
it is in the base class implementation of this UI script. its called BDefaultBuildingConnectedUIImplementation and it has a function that looks like this:
public virtual void Open(IBuildable buildTarget)
{
Debug.Assert(buildTarget != null);
// why are we opening a prompt if the buildable can't even be built?
Debug.Assert(buildTarget.allowedFacilities.Count > 0);
if (currentBuilding == buildTarget)
Debug.LogWarning($"{this} opened while already open.");
currentBuilding = buildTarget;
BOpenCloseEventManager.InvokeUIOpen(this);
Debug.Log($"{gameObject.name} is active: {gameObject.activeSelf}");
gameObject.SetActive(true);
Debug.Log($"{gameObject.name} is active: {gameObject.activeSelf}");
}
its child, the thing im trying to call Open on, calls this function with base.Open()
ok and... from where is THAT code called?
at some point you're doing someReference.Open(something);
I want to know where someReference came from
someReference is this
Looks like it's from a button
public override void Open(IBuildable building)
{
base.Open(building);
can you show how the button listener is configured?
the child class does this ^
But this is disabled/inactive so what's causing everything to trigger?
Could probably ask #💥┃post-processing
there is a separate game object which implements IPointerClickHandler
uhuh and this is called from BBuildTarget.OnEnable
yes show that
basically where is the reference coming from that you're calling Open on in the first plce
public class BSelectable : MonoBehaviour, ISelectable, IPointerClickHandler
{
public event ISelectable.SelectedEventHandler Selected;
public event ISelectable.DeselectedEventHandler Deselected;
public void Deselect() { Deselected?.Invoke(); }
public void OnPointerClick(PointerEventData eventData)
{
if (BSelectionManager.RequestSelection(this))
{
Selected?.Invoke();
}
}
}
this thing has an event
uhuh... and where do you attach a listener to the event lol
other scripts subscribe to that event
cut to the chase
yeah lets follow the chain!
How's the inspector look?
i sent a couple images earlier
editor before starting
For the selectable component?
there is a function subscribed to that function which calls Open on the child and then that calls the parent Open
the function is a lambda
the reference to the popup comes from a [SerializeField]
selectionComponent.Selected += () =>
{
Debug.Assert(buildPrompt != null);
if (built)
{
Debug.Assert(selectedFacilityUI != null);
selectedFacilityUI.Open(this);
}
else
{
buildPrompt.Open(this);
}
};
rught so... selectedFacilityUI
where does that come from
or buildPrompt
not sure which is relevant here
What are those references pointing at?
Debug.Log($"Supposedly Inactive: {gameObject.name} is active: {gameObject.activeSelf}", this);
gameObject.SetActive(true);
Debug.Log($"Supposedly Active: {gameObject.name} is active: {gameObject.activeSelf}", this);```
Which object is highlighted?
buildPrompt comes from this:
[SerializeField]
GameObject buildPromptObject;
which is gotten by doing this:
buildPrompt = buildPromptObject.GetComponent<IInterfaceConnectedUI<IBuildable>>();
It's serialized
that was poorly explained but yeah
surely it's assigned in the inspector
that second line is reading that object, not assigning it
what did you assign to it in the inspector
if i click that, it highlights the gameobject in the scene
this is true for all instances of this clickable object
I see this most often when something is unassigning it at runtime
so im aquiring a reference to the deactivated gameobject from a serialized field
and yeah in the middle theres a click handler followed by an event followed by a virtual function call. and to initialize it theres a GetComponent call
I would try Dalphat's thing now
i dont have IInterfaceConnectedUI<IBuildable> serialized because its a templated type and unity doesnt know how to serialize it so i just take in a GameObject and then call GetComponent
okay excellent trying that now
Unity actually can handle serializing the generic type just fine these days it's more that it's an interface that's an issue.
it highlights the deactivated root object correctly
I would try putting OnEnable and OnDisable on the script and see if something funny is happening inside the SetActive call
You might have an OnEnable that's deactivating the object for example
OH SHIT
i bet thats it
okay so wait
if i have an OnEnable function on a behavior. the game starts, both the behavior and its parent object are enabled/active respectively
and then I disable the behavior
then deactivate the gameobject
then reenable the behavior
then reeactive the game object
OnEnable in that script gets called twice?
I'm not actually sure
Debug.Log would tell you
oh wow
okay so yeah deactivating a gameobject calls ondisable for all components
the solution for me is to make sure onenable doesnt get called more than once
So what was the result?
I'm curious?
Does OnEnable get called twice in that scenario?
i actually cant figure out whats going on
this seems inconsistent but also im testing it in a weird way
can i snap a game object's transform to the center of a grid cell? (2d)
without using grid layout group
i want to know too but unfortunately its almost 2 in the morning and ive got an exam tomorrow lol
thanks for all your help praetor
will update you if i test it
In code? Use the Grid component
what about inspector?
there are cells that the player can snap into, but its not in every cell in the grid
how can i make a system in unity where there is a video playing on a 3d cube but ain't visible untill i hover with another cube on that cube
which part do you struggle with, this is like 3 different problems in one
the visiblity part or we can call it the xray masking system
visibility can be as simple as disabling a game object. Im not sure wat you mean "hover with another cube on that cube". You likely want a raycast here, but you should probably describe more
okay so like there is a cube on which the video is playing but it isn't visible through the main camera and i have another cube that is controlled by my mouse and when i control that cube and hover it over the video playing cube then i should be able to see the video
i still dont get what you mean hover it over, i assume this is like a remote and you are pointing it at the other cube. In which case you would want to raycast from the held cube using its .forward as the direction
Hi everyone, I was wondering if anyone had an idea for a clean solution for generating colliders along a chained bezier curve.
My current thought was to use Sphere Colliders or Box Colliders and place them in steps of some distance (given that I don't need it 100% perfect). However I noticed that the Sphere Collider cannot take an position offset and the Box Collider cannot take a rotation offset.
This is only an issue given I want to put the colliders on a single game object rather then having many / 100's of GameObejcts.
That said, if anyone has a better idea on how to do collision checks for curves I would appreciate the help
A set of shaders for creating mask for 3D objects.
📌 An easy-to-use asset will allow you to view 2 objects (or a group) simultaneously through a mask. This will create, for example, an X-ray effect in the game.
📌 The masking system uses specially written shaders to optimize rendering calls. This means that adding this tool to your project will...
I mean like this
when instantiating a prefab can I pass some vars directly ? instead of passing them after the constrcut
Nope.
You're not constructing the GameObject, unity does.
whats this for, are you making like a rope system? if we're just talking about collisions along a single curve then the easiest way might just be modelling the curve and using the mesh collider
if you make your own static method then yea you could make it feel like you're doing this. but in reality that static method will only end up instantiating and settings the variables itself
Its to make an interactable edge for walls that a player can interact with on collision. The best way I can describe it is kind of like a wall climbing mechanic where there will be ledges on a wall that a player can attach too and shimmy across.
okay ty
Since the walls can be curved I figured the best solution would be to use a curve, this way I can move the player along said curve by just passing in a value for there position.
The only issue is that if I have many of these climbable surfaces in a level then that will be alot of colliders, and even worse on top of it alot of game objects.
maybe you can experiment with runtime mesh generation, assuming this doesnt need to change very very often. i havent done it much personally but I think it'd be better than 100s of game objects like you said.
Ah good shout, a mesh collider could solve this! I could generate a mesh using the curve and then use a mesh collider.
Thank you!
The mesh should be a constant, and wont change, so I'll either write something to pregenerate it or just get it generating on start. I've written mesh gen code before for this sort of thing but I didn't think a runtime mesh could work with the mesh collider. xD
Is there a way to make rule tiles account for other rule tiles? for example, I have these diagonal tiles. Now of course they wouldn't be diagonal if they had a tile of the same type to the top or corner. Is there a way to make it such that it accounts for the existence of any tile rather than just other smart tiles of the same type? perhaps through custom tile scripts? Thanks
this is a code related channel
I assume the answer would be related to custom tile scripting
if you would have some code issues with this exact case then just ask here
make research, try it yourself, when you face issues we can help
Hey everyone, So I have these errors pointing toward this apparently faulty code. It seems to say that
my reference is either bad or absent, but it's there. I have been hitting my head against a brick wall for a hour
Anyone know how to fix this ?
if you are going to post code like this at least include the line numbers
!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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossManager : RoomManager
{
[field: SerializeField] private Boss _boss { get; set; }
public override void ActivateRoom()
{
//Here is line10
_boss.gameObject.SetActive(true);
_gameManager.ChangeZoom(6f);
}
public override void CanBeDeactivated()
{
DeactivateRoomManager();
}
private void OnEnable()
{
ActivateRoom();
}
}
There you go !
still no line number. which is line 10
my bad, mate
so _boss is null. Debug it. chances are you have multiple instances of the script
I never instantiate it, I only have one copy of the gameobject and as I've shown, my serialized field is referenced as it should
still, the run time is not lying. Debug it
if (_boss == null) Debug.Log($"Boss is null on {gameObject.name}",this);
I know it is not lying, I just don't understand how it's null is all,
well if you debug you will find out, that is what debugging is all about
yes, I've been debugging. I have not found a solution, so I'm hoping for some hints, honestly. Do you know what could render it null ?
there are lots of reasons it could be null. First you need to identify exactly where it is null
well right there, it's the only place I reference the object
prove it
I'll give a look through all of my files
that is not how to debug
then guide me, I'm on a wild goose chase, here
start by adding the line I showed and then screenshot your console
I did,
Boss is null on Bossroom
, but we already knew that
no we did not know, you assumed, now we know
and I said screenshot the console so we can see the full stack trace of the error
also if you can show if the reference is still assigned during runtime?
that is not a stack trace of the error
still there
isn't this
Boss is null on BossRoom
UnityEngine.Debug:Log (object,UnityEngine.Object)
Debug:Log (object,UnityEngine.Object) (at Assets/Scripts/Dev/Debug.cs:244)
BossManager:ActivateRoom () (at Assets/Scripts/BossManager.cs:10)
BossManager:OnEnable () (at Assets/Scripts/BossManager.cs:22)
The stack trace ?
screenshot full inspector of the gameobject
There you go !
That gameobject is Boss not BossRoom where the error is on
so it nulls itself ?
show the inspector for BossRoom
Uh can someone help me with something? I got an error I can't figure out.
dont ask to ask please
Sorry, wasn't sure if this was the right spot to ask.
I got this error, and I don't understand it, especially since I'm not using poiyomi on this project anymore. I changed it all to another shader.
if you aren't using it anymore, then just delete it?
I removed it from the folder, and it starts spitting out like a hundred errors
Yep that was it. I had the Manager twice and it fucked everything up. thanks for everything, guys
god, that's annoying, I had removed it, too
I followed the instructions online with creating records: record Alarm(float TimeLength, bool Loop); but it gives an error predefined type is not defined or imported
Did I not say multiple copies of the script? Next time don't just assume, debug
well you didn't
you have exact path of it
I thought you meant multiple copies of Boss, which is why I had turned down the idea, my bad
I put it back in to get rid of the 100+ errors, so it's there now. I'll show what it starts to look like after I remove it
More specifically 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported
anyone using VSCode?
why this gives error? It's the only OnDrawGizmosSelected that show error. The other is fine. The difference between this and the other OnDrawGizmosSelected is that this one is written in VSCode.
we have no idea what are you trying to create
give some context, some code
learn how to share issues and how to ask for help
Im just trying to set up a record to add to a dictionary
Each record is an alarm in a dictionary of alarms
just show the code
that looks like you have the method declared inside another method
there is no such thing as record for dictionaries
wowowowow you are right!! thanks, very embarrassing mistake. Looks like I'm too used to Visual Studio automagically fixing my mistakes.
Any ideas what I'm doing wrong to go from just a few errors to 60+?
the words 'local function' are the giveaway there
and the fact that your braces are misaligned
record Alarn(float TimeLength, bool Loop);
Dictionary < Timer, Alarm > alarmsDic;
public bool initialized;
public void Setup() {
alarmsDic = new Dictionary < Timer, Alarm > ();
initialized = true;
}
}```
do you have your IDE configured?
this error has a lot of spellings and errors
what is Timer? is this your own class, or are you using (you shouldn't) System.Threading.Timer class?
Timer is an enum
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
• Other/None
I dont undertand ive been using unity and visual studio and its works fine my errors are being underlined
And my code auto completes
record Alarn(float TimeLength, bool Loop);
Dictionary < Timer, Alarm > alarmsDic;
what is Alarn and Alarm
I dont have wifi right now im using mobile data so im on my phone , which means i had to use a image to text converter after taking a photo of my laptop screen then correct the mistakes of that app which i missed some put that through a c# beautifier and then post it here
Are you allowed nest IF statements inside of TRY? Will it still catch the exceptions?
yes
yes why not
thank you
Hello, I have a question.
I have a character that uses Character controller for movement. I also have a object pick up mechamic. So when I pick up the object and walk around with it it just goes thru the walls even tho it has a collider. I tried adding another collider to the player that turns on when the object is picked up but it still goes thru the wall. The character stopps when the character controller collider hits the wall but not when any other collider does. Any idea how I can solve this? Thanks
How are you moving the picked object?
If you want it to collide, you should make sure it's controlled by physics.
How can I modify a direction so its vertical and horizontal angles in comparison with another direction doesn't get too far awaiy? Basically clamp it.
I tried this but it's not working:
float3 center = position + aimingTargetCenterOffset;
float3 targetDirection = MathUtils.ClampMagnitude(shootingPosition - center, baseAimingMagnitude);
float3 rotatedBaseDirection = math.rotate(rotation, baseAimingDirection);
float3 axis = new(0f, 1f, 0f);
float3 plane = math.rotate(rotation, axis);
float3 targetDirectionProjection = MathUtils.ProjectOnPlane(targetDirection, plane);
float3 rotatedBaseDirectionProjection = MathUtils.ProjectOnPlane(rotatedBaseDirection, plane);
float angle = MathUtils.SignedAngle(targetDirectionProjection, rotatedBaseDirectionProjection, axis);
angle = math.clamp(angle, -aimingTargetMaximumHorizontalAngle, aimingTargetMaximumHorizontalAngle);
float3 direction = math.rotate(MathUtils.AngleAxis(angle, plane), rotatedBaseDirection);
axis = new(1f, 0f, 0f);
plane = math.rotate(rotation, axis);
targetDirectionProjection = MathUtils.ProjectOnPlane(targetDirection, plane);
rotatedBaseDirectionProjection = MathUtils.ProjectOnPlane(rotatedBaseDirection, plane);
angle = MathUtils.SignedAngle(targetDirectionProjection, rotatedBaseDirectionProjection, axis);
angle = math.clamp(angle, -aimingTargetMaximumDownwardAngle, aimingTargetMaximumUpwardAngle);
direction = math.rotate(MathUtils.AngleAxis(angle, plane), direction);
axis = new(0f, 0f, 1f);
plane = math.rotate(rotation, axis);
targetDirectionProjection = MathUtils.ProjectOnPlane(targetDirection, plane);
rotatedBaseDirectionProjection = MathUtils.ProjectOnPlane(rotatedBaseDirection, plane);
angle = MathUtils.SignedAngle(targetDirectionProjection, rotatedBaseDirectionProjection, axis);
angle = math.clamp(angle, -aimingTargetMaximumDownwardAngle, aimingTargetMaximumUpwardAngle);
direction = math.rotate(MathUtils.AngleAxis(angle, plane), direction);
float3 result = center + direction;
I am just paranting it to the characters torso for now, but I am open to suggestions
Instead of parenting it, move it towards a point in front of the controller via velocity/forces/MovePosition.
Will try that now
if you want to keep it physics based, you can also try a SpringJoint, it will be more flexible, for example knocking the object into something could "break" the spring and make it drop etc.
I will try springs since the moving to the position approach is very buggy
small hint, i prefer to make to put the spring component on the "owner" of the object, not the object that is being picked up (usually the heaviest object should have the Joint, to improve stability)
I've got a single error on a project and I'm so confused about how to fix it. Does anyone have any ideas?
which version of Unity are you using?
2019.3.15f1
which is what the project I'm doing requires apparently
It's TextureFormat? Not TextureImporterFormat? 

that error is all I know
There was two other errors, but by // in the helper.cs it got rid of them. THAT one however if //'d just throws like 65 errors
That is your problem, RBG48 was introduced in 2020.2
is there a way to get around it? I dont even know what its using it in
The error message tells you exactly where it is being used.
You have a choice, stop using the asset, find a version of the asset compatible with 2019.3 or update to at least 2020.2
I don't know if the project will work on 2020.2
and I wouldn't know where to look for that helper.cs
and if I remove the asset it throws so many errors
the full path is in the error message
no, I mean to replace it. I have the .cs opened
so show the code
the whole cs?
the part throwing the error
just comment out the line
I did. I said that, and that it throw like 60 errors if I do, in the vein of:
"Assets\ABI.CCK\Scripts\Runtime\OnGuiUpdater.cs(74,16): error CS0246: The type or namespace name 'Text' could not be found (are you missing a using directive or an assembly reference?)"
So I undid that and it went back to 1 error.
that is totally unrelated
Then why does it happen the second I comment it out? there's TONS of errors that pop up.
because compilation is stopping because of the first error, once you fix that then compilation continues finding other errors. This is totally normal behaviour
okay... so what are THOSE errors then? I'm so confused...
They are telling you what the problem is, can you not read them
No. I haven't used Unity in a few years and I'm trying to do a project but no, I don't know what this means.
my guess is you are trying to use assets which are not compatible with your Unity version so why are you doing this if you cannot fix simple errors?
Cuz I'm literally too poor to hire someone else to do it, no need to make me feel like crap for it
I meant why are you using assets not compatible with your Unity version?
I'm literally following a guide and someone else's tips who was helping me troubleshoot.
The version, the specific version of the assets, everything.
well you've got something wrong somewhere if you have compatibility problems with 2 different assets
Well I have no idea, I've been troubleshooting for four hours, trying to get help the whole time, and on top of feeling stupid for not being able to fix simple errors, I don't have any idea of how to fix it.
Do you know what Text is?
literal text or a file called text or what?
no the Text refered to in the error message
No. Nor do I know the "UI" or "EventSystems" or "InputField" etc
All the same problem.
They refer to classes contained in a Unity namespace
Obviously the code you have is looking in a namespace which is not the same as used by 2019.3
So. First thing to do is find out which namespace 2019.3 is expecting. Then find which namespace the code is using and change it
Okay... it's calling for everything from Text to UI to Unity Engine and more
there are 59 red errors
take them one at a time, you will find that as you solve one, many errors will disappear
Okay, so... let's start with Text. OnGuiUpdater.cs is calling for that... do I have to comment it out or something?
did you not read what I wrote?
Okay, yes I did. But that's what I'm saying. "find the namespace and change it".... Change it HOW is what I'm asking
find out which namespace 2019.3 is expecting
...I have no idea where to look for that. Is it by the cs?
okay, I'm a complete noob when it comes to this. I have no idea what any of these terms mean or where anything is located.
search the Unity 2019.3 docs for the Text class and see which namespace it is in
Still have no idea where those docs are. You need to explain it to me like I know computers but not unity at all.
do you not know how to use Google?
yeah, I do, but it's not helping because google 'where are unity docs' isn't gonna get me the answers I need in a reasonable time...I'm asking you because you're someone who's helping me and knows the answers to the questions I have.
You know as well as I do that unity is not beginner friendly, which is why I"m here asking for help
that is a weird theory xd
I literally googled it
why isn't unity begginer friendly?
to start with think about your google search words.
Unity Scripting API will bring you straight to where you need to be
it has a lot of perfectly begginer friendly learns
Ah yes because you said any of those words to look for. Not just "unity docs"
hardly disagree, unity is begginer friendly with proper googling
if you expect me to think for you, you will be sorely disappointed
I don't expect that, I expect help when I say I need help and someone comes along
i literally searched that.
then as i said, you need to improve your googling skills
if you cannot find docs for "Text" class in unity
if you don't wanna help then don't jesus
Unity is one of the most beginner friendly engines there is though, that's why it is as popular as it is.
I am trying to help, saying that you should improve your googling skills
it is not meant to be offending
googling properly is not an easy skill
or just google "unity docs", and find text in there
i don't really understand what is so hard about it 😄
Yet again you're not making sense. "Docs" had me thinking you mean files on my computer, on computer documentation
that doesnt make much sense
you've never gotten a readme?
readme is a readme, not a documentation
apparently when he said "find unity docs about Text" he meant literally unity docs (online) about Text component
APPARENTLY, you didn't even know!
\
if you didni't understand that and started to look for phyiscla files on your PC then 🤷
You had no idea he meant online documentation either, so how was I, a literal noob, supposed to know that?
but what other form of documentation besides online you expected wtf
did you download entire unity documentation as files on your pc?
I don't know, MAYBE the version of Unity has some documentation with allllll the other files it downloads?
anyway, honest advice, practice your googling skills, cut the offtopic please
again, nooob, how am I supposed to know
this is going nowhere, so let's back up a minute. Can you screenshot your IDE with the code in error shown
I sure can't because you still haven't told me what an IDE is
lol
I don't know these terms.
I give up
again you can just google what is an IDE instead of waiting for someone to explain it to you lol
I can see that I won't get even any simple help here. What a wonderful 'official' server, too busy insulting you because you don't know all these terms when you're literally asking for help and say "I'm new to this".
Thanks for wasting both our time.
You see, the problem is that we are providing help, but you just don't understand it
You need to understand the world we live in, no one (usually) will spend their time, explaining you things, that you can just google in 10 seconds yourself
No one has insulted you btw
You can't get help if you don't understand it
Being told to google what an IDE is is not a personal attack on you. It's what we tell everyone who doesnt know
Googling that is one thing, I can look that up because I"m being told specific terms
'unity docs' when not clear if online or included documentation on the install and not saying what they're even called is not something I can just KNOW
right there instead of wasting 10 seconds writing this answer, you could just spent that 10 seconds to googling what an IDE is, educate on that, then send a screenshot as asked
People expect some basic knowledge when in the general (non beginner) channel
Including that docs are online
I'm here because the error I came here for originally stumped people so I figured it was beyond 'beginner' level bug fixing
but you are a begginer
you came to general channel, where we expect people to know the basics, but you don't even know the core (what an IDE is), so how exactly do you expect us to help you not using programming terminology to help with a programming issue?
did you ever once say "hey you're clearly a beginner, you should take this to beginners"
ehh im done
@rapid pivot Over the course of the last hour I have done nothing but try to help you, in fact I did fix the error you originally came with. However you have done nothing to help yourself. I don't know if you were expecting a magic wand to wave over your problems and make them magically go away, that is not going to happen. You need to put in some effort if you expect help but you seem unwilling or unable to do so
You did what I said I did before coming here. I literally said "I commented it out but then it threw more errors, so I undid it." You have been trying to help and I APPRECIATE that, but you have to realize I also said I'm new to this stuff and don't know these terms. If you tell me the NAMES of things to look up, I'll do it, as I've been TRYING to.
Again, you don't know a term - you google it, instead of waiting for someone to explain it to you and get angry over it that he doesn't want to help, period
Xaxup, if you're not helping this doesn't concern you. Help or don't.
That is how it works, and you need to adapt, not we
You cannot be helped in my opinion without even a basic googling skills, and a understanding how internet works, but good luck on your adventure, i cut off from this talk now
For a custom rule tile script, how can I include tiles which fall under other rule tiles in the list of neighbors?
Adding onto this, I assume Unity itself calls the 'applyneighbors' method? I can't find anywhere else in the project it might be called from.
If you still haven't found it. Here are the docs 👆
hello where can i ask about 2d plat micro here
Depends on what plat micro means
#🔎┃find-a-channel
But you can look here for the most related channel
oh sorry it meant platformer microgame 
Well, if asking about code, go ahead here
If about the art #🖼️┃2d-tools
If about it generally, probably #💻┃unity-talk
Any ideas on how i could create a enum (in c# i suppose) and use it in a VSG ? (Switch on enum)
Or even if it's supported by unity
Enums and switches are c# and have been around long enough to definitely be supported by unity
Not sure what vsg is though
Ahhh, then I have no idea
I recommend just doing code, it's honestly as easy, or easier sometimes
Anyhow, if it is visual scripting, ask in #763499475641172029
Yup
Because of my studies domain i am forced to use VS
Yeah I agree, but we are programmers, I can understand it a bit if your a game designer only that want to test something real fast without needing to bother a programmer for it.
I would love to use C
Hello everyone, I have a strange behavior in my build. After having a headless dedicated server build, lately I started to get duplicate console messages. Any idea why this can happen and how to solve it?? Response would be much appreciated!
Well unity uses c#
Not sure of an engine that uses C itself, but there probably is one
Sorry though, I don't know much of anything about visual scripting. Way too hard to be worth it for me
When i say C i mean all C
Like cpp and c#
And no problem
those languages are notably not C. and if you mean C-like languages or languages based on C then don't forget to include the dozens of others
javasCript......
Adding onto this in case anybody cares at all, this is the solution I came up with. Feel free to critique this if it's inefficient
Well there are a lot of languages that come out of c. Best to not refer to it like that honestly
Edit: ah, laggy discord
Given two vectors, how can I get the individual angles of each axis, and then create the second vector from the first one applying the rotations given by those angles? (I know this is redundant, but my idea is to modify a bit those individual angle axis)
what does "individual angles of each axis" mean?
can you draw a picture of what you want perhaps?
How much I must to rotate the x, the y and the z
to go from the first vector to the second?
Yes
I would skip the "individual angles" bit and just use quaternions
https://docs.unity3d.com/ScriptReference/Quaternion.FromToRotation.html
FromToRotation gives you the quaternion to go from one vector to another
I need the angles because I plan to clamp them
You can still use FromToRotation and then just call .eulerAngles on it if you really want euler angles.
Ok, I will try that
for (int i = 0; i < numberOfObjectsToSpawn; i++)
{
int attempts = 0;
bool positionIsValid = false;
Vector2 randomPosition = Vector2.zero;
while (!positionIsValid && attempts < maxAttempts)
{
// Attempt to generate a random position
randomPosition = GenerateRandomPosition(bounds);
// Check if there are no colliders within the sphere
if (!Physics.CheckSphere(new Vector3(randomPosition.x, randomPosition.y, 0f), minDistance))
{
positionIsValid = true;
}
attempts++;
}
// If a valid position was found, spawn the object
if (positionIsValid)
{
Instantiate(objectToSpawn, new Vector3(randomPosition.x, randomPosition.y, 0f), Quaternion.identity);
}
}
Hi, I have this code for instantiating objects in a random range. My problem is some objects spawn very close to each other and I'm trying to make them spawn further away from each other. I have a "minDistance" variable that I use with the CheckSphere component but it does not work at all.
They still spawn close to each other sometimes even on top of each other.
To help with your research a good technique for this is called Poisson Disc Sampling:
https://www.jasondavies.com/poisson-disc/
you may be able to find an existing unity implementation, or write your own
The reason your CheckSphere code isn't working is because you would need to call Physics.SyncTransforms whenever you add or move a collider before they can be picked up with a CheckSphere.
I have a weird issue.
My selected platform is Android. Play mode works fine with it without any errors or warnings.
However when I want to build the Android APK the following errors occurs (see screenshot)
The errors are related to the Multiplay SDK. The package is installed and I am using it and it works in Playmode. I am not using any ASMDEFs.
The other screenshot shows my build settings.
Any idea why this happens? Can't fix it.
You're not using asmdefs but surely the netcode and unity services packages are
are you sure they're all supported on android?
we had this problem yesterday with webgl and multiplay, check the asmdef inspector for multiplay
yep, #archived-code-advanced message
not compatible with Android
Thanks I'll investigate further
Ah ok so I have to exclude the server script on Android build. Which makes sense anyway since the android is Client only
Thanks for the info. Lucky I just stumbled over it today
That property gives angles from 0 to 360. I would like to have values from -180 to 180. What could I do? This are angles, so I doubt I could just do -180 to change the range.
You can subtract numbers that are greater than 180 by 360.
Ok, I will try. Thanks
What's the best way to go about adding mantling? Basically, if a player runs into a wall and they are close enough to the top of that wall, they snap on top of it. A bit lost on how to do this
are you in 3D?
and are you working with actual walls, or stairs?
the KCC has very good support for stairs in 3D, which is the hard-as-shit case
alternatively, are you in 2D working with walls?
as in grabbing ledges
i'm in 3d, and using a physics based character. this should work with things other than walls as well, and be an instant process. not an animation.
ok, so, I would break this up into a few different problems.
- getting a contact for touching a wall,
- determine if that contact is valid to allow snapping up,
- given a valid contact point, compute the spot where you would end up
- given where you end up, check if that movement is valid.
is there one of these 4 in particular you find more challenging?
2, 3, and 4
1 is fine. i can just do it oncollision enter or with a small raycast
this is my current playerscript btw, if that helps. yes ik it sucks. it's what i'm working with for now
https://hastebin.com/share/ihihokodav.csharp
let’s just focus on the problem at hand
- now you have a contact, and want to know if it is valid. You need to check a few things:
-Contact normal must be in a good direction towards player.
-The thing you are contacting allows you to snap up (eg ground layer or something).
-Player facing direction is oriented towards contact point (probably? unless you want to snap up while walking backwards into a wall)
i would make a separate script for all of this btw
- Now we know that the contact MIGHT allow us to snap up. So we need to find the relevant spot we would end up. I’m not super familiar with the 3D physics queries, but you need a method that lets you find a point between two points on a collider. Specifically, you need to search between contact point and contactpoint + some max snapping vector. We’re searching for the wall’s ceiling (potential new floor). From here, we can calculate the point our player would be at.
If no valid point is found on the collider, then cancel
- now we know where we would end up if we did snap. First, we need to check that area. Again, we need 3D physics queries, but we’re basically looking for an OvelapCollider method. Somethinng where; If the new spot would have us colliding with a wall/ceiling etc, cancel
make sense?
pretty sure, yeah.
check the Collider3D and Physics classes for relevant methods.
perfect, tysfm
also, if you have the time and want to, do you have any quick tips for level design? i know a lot about combat arenas, balancing, enemy positioning, functional stuff, etc, but do you have any advice for how to make an area feel distinct and memorable? (i saw you have level designer in your profile, that's why i asked)
Theming is the most important skill you can have when designing levels or games. Here, I describe the very basics.
Maker ID: Q1C-F5R-82H and PJT-7QY-SWF
0:00 Intro
0:36 What is theming
2:02 Types of theming
3:23 How to theme
7:05 Put it all together + Examples
10:06 Outro
------------Links:------------
My Twitch Stream: https://twitch.tv/loup...
Theming is the core
good to know, ty :)
hello am trying to make a player pref that i can change the name in the editor but i have no idea how to do this:Exsample
public string Key;
PlayerPrefs.SetInt(Key, 10);
so what is the issue exactly?
PlayerPrefs.SetString(playerNameKey, playerActualName)
i dont now how to change the name in of the player pref whit a string in the editor
how to change the name of the player pref in a editor?
do you know how player prefs work?
you can change the player's name, set it in the player prefs
then you can read it whenever you want
which one would be better to use?
I feel like I should go with the second one since it has seperate InputManager class and more organized. But it handles movement every frame.
In the first one it only moves if there is an input.
https://goonlinetools.com/snapshot/code/#z02iwk7r88n9kd4cuz0mzl
or
https://goonlinetools.com/snapshot/code/#nrpju7u0itx719lcigvlb
InputManager is better approach
as it gives you more contorl
and it's better in terms of single-resnposnbililty rule
the point is that i dont want the player prefs to have the same name i want them to be different so the most logical think to do is to change the name of the player prefs but to change it i want that to happen via string in the editor
Yeah thought so, thank you
seems like you don't understand how player prefs work
in player prefs you can STORE certain data
and ACCESS it
you have player name, you can save it in the players pref under a certain key
and then retrieve the name by that key
if you have the name in a variable, you can save it under any key
It seems kinda like playerprefs may not be exactly what you want too. Have you looked into more robust save methods, like using JSON, or Binary
oK am going to tell you in the most simple way possible i want to save a number but this number needs to be stored whit in different keys so i want to have the posibility to change the name so i dont have to make 1milion player prefs to save the same thing
i want to store a simple number is not that complex
yes
why?
I would still recommend anything over playerprefs. But it's your choice
what is not working with this?
i think you just don't understand properly how player prefs works
this statement makes no sense
it doesn't
@jaunty iris
why would you store the same number in 100 different keys for example?
i imagine you are making some kind of multiplayer game with X players
and want to save each player name in a player prefs?
no okay it's not the case
since you want to save the same value under different keys
then honestly i have no idea why would you need to make such a thing
can you just tell my how to do it
but i can't understand your english im sorry
i don't even know what are you trying to do
why do i have to tell you
no, explain exactly what you want to do and why you want to do it, I have a feeling this is a typical X Y problem
They did not understand your original question and are asking you to explain better.
My interpretation: I want many keys with the same value but I don't want many keys.
I TOLD YOU I JUST WANT TO NAME THE KEYS IN THE EDITOR IS IT THAT HARD TO ANSWERE just dont say anything
Then do that. I don't know what it means, but go for it
what is wrong with the code you posted earlier?
ok bye bye you can`t help
bye bye 😦
i just think you can't be helped as you can't even specify with proper english what do you actually want
that's pretty much all you need:
public class SomeClass : MonoBehaviour
{
public string Key;
public void Save()
{
PlayerPrefs.SetInt(Key, 10);
}
}```
Is there a way to get your custom InputAtcionMap from an InputActionMap assigned through editor?
We're not certain. What if they're wanting to change to key while maintaining the same value and without introducing new entries to the player preferences?
We will never know what did he want, as he can't properly say it
You would have to have a managed version for that. Using stuff like OnValidate and other editor based methods.
Abways, anyone know?
you want to get an InputActionMap from assigned InputActionMap through editor?
doesn't make much sense
I want to cast to my custom InputActionMap from the generic InputactionMap that I can assign in editor
you have a class that inherits from InputActionMap?
So I have PlayerActionMap that is generated from my action map, but that doesn't serialize in editor feilds. But I can assign it with InputActionMap, but I can't cast to my generated map from it.
you won't be able to directly cast it from the InputActionMap to your custom generated map
Wait there is a inpput-system specific channel
yes you might ask there for someone more familiar with it
do I have a way to access the name of a scene loaded additively via the scenemanager API?
you know the scene's name, you added it
why do you send me this
my bad
No, this is for editor related code. I can load multiple scenes during editing time, when I press play, I want to know the name of the active scene
sometimes discord ui is fuzzy
you don't
i see. SceneManager.GetActiveScene()
Yeah, unfortunately it returns the first scene and not anything else beyond that
I don't
but you can
It's added during edit time
hmm... i don't know what to say. it's the active scene isn't it?
still, you can
How so
the first scene is always the active scene in the editor i guess
I don't want to manually input if I can avoid it
You can just access all the scenes added to the build.
you can do the last scene, i think it's the last scene in scene manager, the order in the hierarchy matches the order in SceneManager
So do you want to access the scenes that aren't added to the build?
Okay, you know how th editor now supports editing multiple scenes simultaneously. Well the first scene you add in the editor will be the one returned by GetActiveScene(). I want the last. There's only 2 at all times for my use case
No, they're in the build
I see. You can use SceneManager.GetSceneAt(int)
ActiveScene is a special concept and not really that important
also SceneManager.sceneCount if needed
Thank you all. Issue was solved via Scenemanager.getsceneat
Just a thought but SceneManager.sceneLoaded and SceneManager.sceneUnloaded might also work
Right it depends on use case, but when the scene is loaded just store the name?
yes, it will work, but it's too complicated
if you have to find the names of the scenes, use this instead
int sceneCount = SceneManager.sceneCount;
for (int i = 0; i < sceneCount; i++)
{
Scene scene = SceneManager.GetSceneAt(i);
myScenes.Add(scene.name); // assuming myScenes is e.g. List<string>
}
why?
because GetSceneAt only operates on loaded scenes
it doesn't operate on scenes that are currently loading or unloading
which are included in sceneCount
I see, I'm sorry, you're right.
Get the Scene at index in the SceneManager's list of loaded Scenes.
📃 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.
Im trying to make normal touch controls(player look) for a mobile fps game, this thing doesnt work as intended, it works to some extent but you can swiper left to right and it spins out, also sometimes somehow it collides with left touch controls(joystick-movement)```cs
foreach (Touch touch in Input.touches)
{
if (touch.position.x > Screen.width / 2)
{
touching = true;
mouseX = touch.deltaPosition.x * mouseSensitivity + xRecoil;
mouseY = touch.deltaPosition.y * mouseSensitivity + yRecoil;
}
else
{
touching = false;
mouseX = 0;
mouseY = 0;
}
}
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -40f, 40);
transform.Rotate(Vector3.up, mouseX);
fpsLook.localRotation = Quaternion.Euler(xRotation, 0, 0);```
What's the unwanted behavior?
managed to fix it with chat gpt
ObjectScriptableObject inherits from ItemDataScriptableObject
I'm referencing a script that could either be that ObjectScriptableObject or another script, and I want to run this function when it's this one of the two
is there a good way to do this?
if (theReference is ObjectScriptableObject oso) {
oso.Whatever();
}```
However this is kind of an antipattern, if you're doing this there's something wrong with your code architecture in the first place
the point of polymorphism is to not care about the underlying type when dealing with the parent type
Ah yeah, you're right
The reason for doing it was to check if the item I'm right clicking with is a block (to place) or an item/tool (to use), I guess having a function in the inherited script that's different in the different inheritors would make more sense
Ideally you'd have like a single Use() method
Or abstract properties on the base class like public bool IsPlaceable / public bool IsUsable
but I wouldn't bite too hard by type comparison
unless you're checking more than a few types that is
{
switch (nextState)
{
case AiState.Fight:
yield return fight (target); // I DO NOT WANT THIS TO EXTEND PAST HERE
break;
}
_state = AiState.None;
}```
Is there a way to stop the couroutine within the fight coroutine? I have a condition thats met in this coroutine but when I do yield break it comes back here, is there a way to have it not return here after fight is done?
yield break; exits the coroutine
the moment you yield break, it is over
if you want to just "fire and forget" the fight coroutine and quit this one immediately without waiting for it to finish, you can do this:
StartCoroutine(fight(target));
yield break;```
you could also just run the coroutine in it
like IEnumerator fight = fight(target);
while (fight.MoveNext())
yield return fight.Current;
I mean... sure but that's identical to yield return fight(target);
i’m just mentioning identical options
so he gets the concept of how they string together
To make it clear let me explain what this is actually doing:
{
float minAngle = 5;
while (HasSight())
{
float angle = AiCalculations.IsFacingTarget(transform, target);
if (angle < minAngle)
{
Action.Invoke()//This leads to next function
}
yield return null;
}
}```
``` public void EnterState(AiState nextState, Transform target)
{
if (_stateCr != null)
{
StopCoroutine(_stateCr);
}
_state = nextState;
_stateCr = StartCoroutine(HandleNextState(nextState, target));
}```
Pretty much the action will lead to this function which should in theory end the previous ienumerator.
However that loop just keeps on running for some reason it wont stop..
given that you probably really want to make sure fight coroutine is only ever running one at a time (probably?), I would use Praetor’s method, and store a fightCoroutine variable, where you check if it is null
Pretty much the action will lead to this function which should in theory end the previous ienumerator.
Huh?
I don't see what this has to do with the previous code you posted.
and also have no idea what that sentence means
or what Engage has to do with EnterState
I'm looking for a way to stop the iterator completely, i edited the code out to make it easier to read.
yield break; stops it completely
if you run StartCoroutine(HandleNextState(nextState, target)) again it will run again, naturally
the iterator stops itself with yield break. Other code can stop it from StopCoroutine, but that only stops the call from beginning next time coroutines are run
like, if the coroutine calls other code that eventually calls StopCoroutine on it… it’s still running until it hits the next yield
ill try yield break again, maybe the structure is wrong
This all seems very complicated, so you're likely getting lost in the weeds
probably getting confused between multiple running instances of the coroutine
IEnumerators are great once you get the idea
I think I'm kinda confused as to whuy HandleNextState is a coroutine at all?
{
_pathfinder.SetVelocity(Vector3.zero);
float minAngle = 5;
while (HasSight())
{
float angle = AiCalculations.IsFacingTarget(transform, target);
if (angle < minAngle)
{
OnActionRequest.Invoke(this,aiAction);
}
Vector3 lookDirection = target.position - transform.position;
_pathfinder.SetRotation(Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(lookDirection), Mathf.Clamp01(1 * _lerpSpeed)));
yield return null;
}
}```
Heres the unedited version. The Event here is to ask the AiMaster if this enemy can attack
The code you showed above was HandleNextState
This is because it's called from an Ai Manager rather than its own script
It's unclear to me which coroutine you want to stop
The engage coroutine
{
switch (nextState)
{
case AiState.Move:
yield return _pathfinder.MoveToTargetPosition(target.position, 2);
break;
case AiState.Engage:
yield return Engage(_attack1, target);
break;
case AiState.Fight:
yield return Fight(target, _attackIndex);
break;
case AiState.Dying:
yield return Die();
break;
}
_state = AiState.None;
}```
The problem is you're doing this:
_stateCr = StartCoroutine(HandleNextState(nextState, target));
So when you do StopCoroutine(_stateCr) it's not the actual state coroutine you're stopping
it's the HandleNextState one
oh
which isn't actually doing anything in the first place
Is there a reason HandleNextState is a coroutine
I feel like what you actually wanted to do was this:
I thought it involved whatever coroutine its working on atm
private IEnumerator HandleNextState(AiState nextState, Transform target)
{
switch (nextState)
{
case AiState.Move:
return _pathfinder.MoveToTargetPosition(target.position, 2);
break;
case AiState.Engage:
return Engage(_attack1, target);
break;
case AiState.Fight:
return Fight(target, _attackIndex);
break;
case AiState.Dying:
return Die();
}
_state = AiState.None;
return null;
}```
Yea its a coroutine because i thought doing StopCoroutine(_stateCr) would allow me to stop whatever coroutine its currently using at the time, whether it be fihgt move etc
no
DO this
_stateCr = HandleNextState(nextState, target);```
you don't want it to actually BE a coroutine
you just need to do this
I'm getting these unreachable code detected here
you're missing the return null; at the bottom
read the error
ahh
then do this outside:
IEnumerator coroutineToRun = HandleNextState(whatever);
if (coroutineToRun != null) _stateCrt = StartCoroutine(coroutineToRun);```
Also, those breaks are not reachable because you return directly before them
So IENumerator is the specific function inside the class where as coroutine is an instance of the function
im trying it now
Not really. IEnumerator is the interface Unity uses to build coroutines on top of
{
switch (nextState)
{
case AiState.Move:
return _pathfinder.MoveToTargetPosition(target.position, 2);
case AiState.Engage:
return Engage(_attack1, target);
case AiState.Fight:
return Fight(target, _attackIndex);
case AiState.Dying:
return Die();
}
_state = AiState.None;
return null;
}```
so are those IEnumerator methods? like Die()?
yea so basically they are a way to sequence everyting, the ai master detects when the AI is in a none state to process its next action. As for the Die ienumerator that also has an event at the end to say the animatino has completed then the ai master will then remove the object from the scene via fade or whatever
So with this one its not returning from the IEnumerator once its done, is this intentional?
{
_pathfinder.SetVelocity(Vector3.zero);
float minAngle = 5;
while (HasSight())
{
float angle = AiCalculations.IsFacingTarget(transform, target);
if (angle < minAngle)
{
yield return Fight(target, _attackIndex);
break;
}
Vector3 lookDirection = target.position - transform.position;
_pathfinder.SetRotation(Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(lookDirection), Mathf.Clamp01(1 * _lerpSpeed)));
yield return null;
}
}```
I ended up going with this
``` if (angle < minAngle)
{
yield return Fight(target, _attackIndex);
break;
}```
Well if the loop never ends it will never return
guys I am new to unity and I need to start working with the grid components . but all the documents I read are like stuff that is flying over my head . so is there any documentation that could make these concepts in unity easy to understand. also I don't like watching YouTube videos as I feel those would limit me in what I can do .
do refer me some good documentations for reference please.
Unity manual.🤷♂️
If stuff is flying over your head, you probably miss some more basic understanding, so get back to the basics.
Why is this called twice? ```cs private void OnTriggerExit2D(Collider2D collision) {
int notProtectedDamage = attackDamage;
int protectedDamage = notProtectedDamage - 1;
if (!Attack_Player.instance.isProtected) {
Player_Stats.instance.health -= notProtectedDamage;
}
if (Attack_Player.instance.isProtected && collision) {
Player_Stats.instance.health -= protectedDamage;
stats.health -= 1;
}
}```
Debug the collision to get the name of the gameobject
I think I know. I forgot I have two colldiers on the object. 🤦♂️. How can I add collision in the "if" statement?
This code is a child of an object that also has a collider. This object (Child) has its own collider as well*
if (collision.gameObject.CompareTag("Something"))
Is a good check
Or
if (collision.gameObject.TryGetComponent(out SomeScript script))
But yeah, you'll want to check what object is triggering it somehow
It is called on the player and the object? This object is an enemy
I'm not sure. Is that the debug showing the names above? So _Player 1 and Attack Pos?
Yes, I used print(collision.name)
You just need to check what you're colliding with
#archived-code-general message
Validate the data before using it
Your correct. Its the Player that the enemy is colliding with. The player also has two colliders and those names are of the player
Is there a way not to use Compare Tag?
Yeah, the second one I showed is good
I didn't see that. Thanks
You can also check the layer
Another question: Are you familar with AI movement using the Navigation System?
Somewhat. You mean the one in Unity itself right?
I think so
I have an issue understanding how I can tell the enemy to stop and attack. Currently it stops when its close to the player and attacks, but when the player moves a little away, it starts moving again.
This is the code ```cs void MoveAndFlipAnimation() {
bool isAliveandCanFollow = movementScript.canFollow && !stats.isDead;
bool attackIfPossible = movementScript.canFollow && movementScript.agent.velocity == Vector3.zero;
if (isAliveandCanFollow) {
if (attackIfPossible) {
ChangeAnimationState(Attack_Skeleton);
}
else {
ChangeAnimationState(Run_Skeleton);
}
} else if (!stats.isDead) {
ChangeAnimationState(Idle_Skeleton);
}
}```
Well, you're gonna just have to play with stop distances and attack range. Make the attack range large enough compared to stop range so they can be guaranteed a hit even if they start moving. For example stop within .01, bit attack at .5 or something.
Or you can go the route of attacks hitting even if they move before the animation of the attack completes. Like as soon as they stop it goes through
I don't think I explained what I needed. I want the Enemy not to follow the player mid attack. I want it to wait until the attack animation is done.
Ohh, gotcha.
Either look into animation events (send an event when the animation completes, and halt movement until that is received)
Or use coroutines where you disable movement, yield return WaitForSeconds or until something, then enable movement again
THANK YOU! I totally forgot how useful an animation can be. All I needed to do was go to the Attack animation and start record. Then I just checked off the movement script at the start of the animation, and a bit before it ended. (Even though I can't really adjust attack speed, etc this is all I needed)
what kind of game are you making?
and what is your prior experience programming?
I have around 500-1000 particles. Their positions are known and given. I create particles (using pool system) and play them but now, I would like a better more efficient way. Can I use just one particle system and give it some points to play instead of playing N different particles ( particle system)?
Pooling for this sort of scenario wouldnt benefit much, instead gpu instanced them
Is this unitys particle system or your own?
yes, particle system unity.
I don't want to use ECS unless I have to do it
I think particle system has an api to give points and then plays it
i get null reference in my code , i try to find the problem and am sure everything fine , it only work when i delete the prefab and put is in the game again , and even after i solve it like this after a while it give me null reference again
look at the line it is telling u
What is "field.setValue(null, cvar) in this case that the first param is null?
The object whose field value will be set.
I assume its some static field
i look am sure the code fine , as i said it for some reason it work again if i delete the object prefab and put it again in the game without changing the code or the references
you can be sure all you like, you have errors and the code is telling you it. If you're absolutely sure the code isnt the issue, why ask in a code channel
where else i should ask my problem then ? guide me : )
you should post your !code and let someone help you to know why something is null
📃 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.
What do you mean just one particle system? 
I'm expecting a particle manager. And it creates its own particle pools.
You make a new particle manager object whenever necessary.
I have a strange error. I Use the System.IO.Directory.CreateDirectory to create folders and it seems to work great.
However in certain programs (Houdini) when looking att the filepaths there is a little wierd symbol at the end. Its generally not a problem
but recently we had to upload a bunch of files and directories for farm rendering and then this little sucker made it inpossible.
In windows, untiy and most other places the symbol doesnt show.
It looks like this:
sorry for the bad resolution, its kind of like a questionmark within a circle
show code
string projectCacheLocation = cacheLoc + "/" + projectName;
if (!Directory.Exists(projectCacheLocation))
{
Directory.CreateDirectory(projectCacheLocation);
}
projectCacheLocation is just a string with file path:
string projectCacheLocation = cacheLoc + "/" + projectName;
Hello Unity Developers, I have a critical issue in getting stream of event in device using Particle.io.
https://api.particle.io/v1/devices/events?access_token=6f7b7b2528634379f919822304162cafa2ffd481
You can check my api endpoint from the above.
Please help me how to get event data from this api.
first thing I would suggest is to use Path.Combine to create your path string
Ok
I will look into that, could that be whats causing the problem?
it's possible, yes
Thank you
Its wierd that i hardly shows anywhere and its just in a very specific program till it comes up
it is odd but unfortunately there are many factors which could be causing this so it's best to reduce the potential for error as much as possible
By passing null as the object, we indicate that we're modifying a static field, not an instance field
Hello everyone
I have a question regarding working with assets
I roughly want to do this: for example, build a prototype of a game purely based on primitives (cubes, spheres, etc.)
And then I want to replace the views of these objects in a couple of clicks
Conventionally, how to mark the renderers with some kind of ID in the addresses, store a bunch of assets on your server. with these IDs, and make some kind of storage editor tool in Unity so that you can rip these materials/textures from the server according to IDs and immediately insert them into the components needed according to these IDs
There are 2 questions:
- perhaps someone has worked in this regard with addressables and can tell you whether this is realistic through them
- if not addressables, then what is the best way to organize this? There are no problems storing texture materials and other things according to IDs, the question is how to adequately load them into the objects themselves according to IDs
Thanks
I want a solution to the problem guys
The solution is in the error message, just do what it says
the actual solution is to stop using the Standard Assets since they are old and outdated and use the Starter Assets instead
thank you so much man
How helpful are state machines in handling enemy AI?
Or determining of a set of doors are locked/broken into/barricaded...etc?
I am just trying to find out if the Timeline Playable Clips and Track stuff still uses IMGUI or if it supports UITK
In regards to Property Drawers
State machines are great for one of these two things, why do you ask?
Hi everyone, I posted yesterday about creating a custom collider for recognising when an object comes near a climbable wall, the solution that was found was to use a collision mesh and generating a custom mesh based on the shape of the wall. I have done this now (see the pink shape in the image) however I have noticed now that we can't make triggers from non-convex shapes.
Is there a way around this? If not I will just use a series of box colliders, (with this aswell, is there a way to create box colliders with a rotation property aswell as I would like to avoid creating potentially 1000's of game objects when instead I can have 1 with many colliders on it) If not thats fine but wanted to ask.
I realized using Unity's event system would be pretty horrible and clunky when we have different mechanics, because doors need to behave differently when barricaded with different materials, different puzzles need to be 'active' or 'inactive' depending on if they're done, and need to have different 'types' of puzzles displayed depending on what kind of triggers the player has activated
You could try to use Physics Layer and have your collider non-convex/non-trigger. (Disable interaction between this layer and other. Use Physics querries to find out if you should be climbing)
That's a good idea, would querying this each fixed update be faster then just using many other box colliders?
Hey could someone teach me to add .json to my vr game
Why the player animations not work after i created an andoride build
It would probably be faster to use multiple BoxCollider. That being said, there is a burden in placing those
However, you can still stagger your querry instead of doing it everyframe which could potentially be more performant.
Hmm, I'll have a think and will try and implement a debug version for both approaches to see how performance goes! Thanks for the help ^-^
Hello everyone. I'm trying to make a third person shooter but I'm having trouble understanding the process to detect a hit. At the moment, I spawn a bullet prefab moving forward using a code found in a tutorial. But this code calculates the end point of the bullet and doesn't check if this bullet collides with something which might have moved in between while the bullet is flying.
I've tried to add a collider enter trigger to destroy the bullet if it is blocked by something but strangely, it still pierces the mesh and keeps going forward until its end.
private void Update()
{
float before = Vector3.Distance(transform.position, targetPosition);
Vector3 moveDir = (targetPosition - transform.position).normalized;
float speed = 200f;
transform.position += moveDir * speed * Time.deltaTime;
float after = Vector3.Distance(transform.position, targetPosition);
if (before < after)
Explode(false);
}
private void Explode(bool hitSomething)
{
if (hitSomething || explodeOnNoHit)
{
Vector3 moveDir = (targetPosition - transform.position).normalized;
ParticleSystem ps = Instantiate(sparks, targetPosition, Quaternion.identity);
ps.transform.LookAt(transform.position + moveDir);
}
Destroy(gameObject);
}
private void OnTriggerEnter(Collider other)
{
if (Config.Layers()[other.gameObject.layer] == "Ground")
Explode(true);
PlayerController player = other.GetComponentInParent<PlayerController>();
if (player != null)
Explode(true);
}
Here is my code. I'd like my bulelts to have a max range. If something is hit in between, the bullet expldoes
This code in Update doesn't make a lot of sense.
There's a particle explosion when it collides with something
Anyway if you want physics interactions you need to move your objects via physics
not with transform.position
You need to use a Rigidbody
give it velocity or add forces to it
The tutorial I used said rigidbody is not really reliable when using mutliplayers and I wanted to add this feature later on
I have no idea what that means
So they gave this code instead
moving via the Transform like this means it's going to teleport through objects etc
I think you're way too early in your Unity journey to even dream about multiplayer anyway
not that that statement makes any sense in the first place
And the bullet won't teleport the same with a rigibody?
Rigidbodies are physically simulated
using the physics engine
they will collide with things realistically etc
And physically simulated objects don't behave the same as simply moving the transform?
A rigidbody is also required if you want to use OnTriggerEnter or OnCollisionEnter
no they do not
they behave according to the rules of physics
But aren't those physics rules simulated, meaning it would still be moving the transform in the end ?
directly moving transforms yourself, is the same as teleporting. Physics run on their own timestep
Ah, I see. That does change the logic then. Thanks for clarifying. I'll try with the rigibody then.
rigidbody ideally says "i slammed in this wall, i cannot proceed" so the transform stops where it needs to
Got it. Thanks!
Of course but it's better than you doing that physics simulation yourself
hey guys
i'm having some trouble i'm my code that i can't manage to fix
there's a video of me explaining the bug and showing it
nice graphics :p
please post code in links
!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.
okay,
i have a function that takes quite a while with doing a lot of raycasts so i want to do it on a difrent thread, is it still usefull if i need to define this many variables ?
thanks :)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
np!
here's the code of my inventory system
whats a managed type ?
so is the problem only when you switch item or
what is supposed to be happening and what is happening instead ?
yeah. when i pick the ground item and then try to equip another, the ground item is still in my hands
and that's not supposed to happen
i need it to be deactivated
you have a lot of if statements that need to be throughly checked
many conditions here
sounds like lastOBJ might not be properly setting or something
how can i avoid using so many if
its not so much the quantity (although avoid nesting by using return statements)
but things like if (index >= 0 && index < items.Count && items[index].itemAdded && items[index].eventHandler != null)
thats a very long if statement
any of those can fail
in the inspector, the lastOBJ is switching properly
got it
is this supposed to set it inactive. ?
if (handScript.lastOBJ != null && handScript.lastOBJ != items[index].eventHandler)
{
handScript.lastOBJ.SetActive(false);
}```
start using Breakpoints to your advantage
its easier tbh when you visually see what your code is doing
Hmmmm okay
public class MovingPlatform : MonoBehaviour
{
public float speed = 1;
[SerializeField] GameObject[] waypoints;
int currentWaypointIndex = 0;
private Vector3 lastPosition;
public Vector3 direction => waypoints [currentWaypointIndex].transform.position - transform.position;
// Update is called once per frame
void Update()
{
if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
{
currentWaypointIndex ++;
if (currentWaypointIndex >= waypoints.Length)
{
currentWaypointIndex = 0;
}
}
// Move towards
transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
lastPosition = transform.position;
}
}
Anyone have any idea why this cube of mine just keeps going forever in one direction?
I wanted it to go back and forth between the two waypoints
I have the pool system for it but using just one particle system is more efficient.
There are n ripples with specific positions.
I know I can spawn one particle system for each and pool it but having one particle system for all of them and set their positions is my desire
Anybody knows why this is possible? Position doesn't have a member called xy. Is this a Unity/ECS thing or a C# thing?
says it right there Unity.Mathematics
xy is a float2
float3 is a custom struct and it has that xy
there is also xx
Mathematics is the DOTS math package, yes
You can use it wherever, but that was what it was made for afaik
it's because in this case transform is a LocalTransform whose Position property is a float3 unlike the Transform class which has a position property that is a Vector3
Is HDRP worth it right now or is it better to go with URP still?, i plan to make a project only for computer and not mobile platforms
this is a code channel
where do i ask? there are many channels i get lost easily
probably #💻┃unity-talk
ty
Maybe #archived-hdrp if you just want to know about the current state of it
I recently just learned about instances. How should I correctly use them? I am making an enemy and a bunch of scripts need reference to the main stat script, how will this look like if I needed to grab the stat script from around 5 scripts, of done correctly ?
I recently just learned about instances. How should I correctly use them?
This is a very confusing sentence. Are you talking about the singleton pattern with a static field namedinstance?
Every object in your game is an "instance" technically
StatScript stats = GetComponent<StatScript>()
?
I meant this: Public static StatsScript = instance.
static variable
So you are talking about a Static Accessor.
But that is not how you would do it
public static StatsScript instance
No equals sign before the name
Then you access it with StatsScript.instance;
although what you typed is not really what it looks like
Look at the singleton page here
https://unity.huh.how/programming/references
I understand how to access it. Let me explain my question again: I want to know how can I organize my code well with using it. I once saw a video talking about how using Public variables aren't the best way to do something since changing the variable will affect all the other scripts referencing it. I'm wondering how can I use instances without having this being a problem.
google c# properties
Well you should be using a readonly property so nobody can change it anyway.
e.g.
public static StatsScript Instance { get ; private set; }```
Instance isn't quite the right word here
You're talking about a static variable that happens to be NAMED instance
But note that doing what you said makes it so there is only ONE StatsScript variable in existence. If you want more (like enemies have one, the player does, ets) then this is not a good pattern
If you have more than one actual StatsScript instance, then having that static variable will cause chaos
I only have one EnemyStat script. That is the static one that all the other scripts reference.
The script is not static, a variable is. Right?
So all Enemies share the same stats then?
Yes
if the script is static, then you dont need to use singleton, use static class instead
btw i think you need to understand what is static keyword first
I'll check out the static keyword*
Did you read this?
#archived-code-general message
You're just talking about a singleton it sounds like
No. Let me do that.
Yes it is a Singleton.
I am having no problem with it, but I already noticed how many scripts I am using Skeleton_Stats in. I have two currently, Attack_Player(on player object), Skeleton_Animations(on enemy).
I just want to know a way I can prevent issues.
So it sounds like you're wanting a singleton database to grab different stat values from.
That seems reasonable.
What issues are you having?
I'm working on a multiplayer game and I have a reticle as a raw image under the canvas
but the reticle script needs to modify the camera script attached to the player
which worked fine when the game was single player
but now that players are spawned in upon joining the game, I need a way to give the reticle a reference to the player
but not to other players
i'm using mirror
maybe I could give the player prefab a reference to the reticle and then assign its reference from the player script when it spawns?
I have code that checks if my player is shielded. If it is then a new animation plays, if the player is shielded the enemy also does less damage. On top of that the player also can't move when shielded.
There are a total of three scripts accessing isProtected: Player_Animations(on player), Player_Movement(on player), and Skeleton_Attack(on Enemy). * sorry for the confusion 😅
I'm using Json.NET to serialize to JSON. I want to make a breaking change to a save format -- I'm completely throwing out the old one, but I want to correctly handle the case where a player has an old save file.
In JavaScript, I've just added a "version" field to the save format, and checked that before loading the save.
But this doesn't work with static types -- the old save file will not decode correctly at all.
How do people deal with this?
I am thinking of adding a version field, and also having a class that just looks like...
[System.Serializable]
public class JustTheVersionNumber
{
public int version;
}
I'm pretty sure I could deserialize the save file to this class (throwing out almost all of the data)
If I can do that, then I imagine I can just keep the old classes around, and deserialize to the appropriate one based on the version number
[System.Serializable] public class OldSaveFormat { public int money; }
[System.Serializable] public class CurrentSaveFormat { public float money; public float health; }
...and I could write methods that upgrade an old save format to a new save format
I am just curious what other people have done in this situation.
Any idea on how to send invites using unity friends and lobby service
https://docs.unity.com/ugs/en-us/manual/friends/manual/concepts/message
https://docs.unity3d.com/Packages/com.unity.services.friends@1.0/api/Unity.Services.Friends.IMessagingService.html
FIX FOR ANYONE SEARCHING IT UP ON THE SEARCH TAB
public class MessageFriend
{
public string message;
}
public async void SendInvite(string memberID)
{
MessageFriend message = new MessageFriend() {message = "data" };
await FriendsService.Instance.MessageAsync(memberID, message);
}```
and you recive it via
void SubscribeToFriendsEventCallbacks()
{
try
{
FriendsService.Instance.MessageReceived += e =>
{
Debug.Log(e.GetAs<MessageFriend>().message);
//DISPLAYS > "data"
};
}
catch(FriendsServiceException e)
{
Debug.Log(e);
}
so if I have an assembly definition file for my code, and one of the editor scripts in that code requires access to URP, HDRP, or Builtin(whichever one is currently in the project), how do I set up the assembly definition file for that?
I believe you can just install both the URP and HDRP packages, then add references to the relevant assemblies
It says it'll ignore any missing assembly references.
you can also use Define Constraints
can I then copy that to my main project(with only builtin in it) and itll keep all references when I export it as a package?
I'd expect so. Each one will reference an assembly definition asset.
So it'll complain that there are missing references
sounds like navarone knows more than me here, though :p
but idk specifically URP/HDRP but im sure they have their own define
Here's how Shapes does it
I need all 3 pipeliens available to a specific code file, can this do that? I saw this but I dont see the defines listed anywhere
ooooo ok!
So all of the packages were installed when it was set up
There's nothing wrong with having both the HDRP and URP packages installed
(all that matters is which SRP asset is selected)
understanding that made me a lot less afraid of messing with render pipelines
this screenshot is from an HDRP project
thanks!!!
also then is there any way for me to have this influence some #defines in compute shaders when they get compiled?
not sure on that front
I guess you'd just look at the currently defined symbols normally
All that this does is tell Unity you'd like this assembly to be able to reference every assembly in that list, if it exists.
Once you have those references, things will behave just like you didn't use an assembly definition at all
awesome! thanks!!
Random q but does anyone know when the first package for cinemachine ever released?
Not really a code question. Better for #🎥┃cinemachine or #💻┃unity-talk
But to be clear, do you mean BEFORE or AFTER it was acquired by Unity?
oh my bad, I always tend to forget this is a code q only channel :) uhh I'd say after
Oldest one I see is 2.1 for editor version 2018.1+
Not sure more than that
Hey, I'm working on a 2D mobile game that's close to Rythem games (like Beatstar), there's a a block falling (UI Image), and there's an area that if you time it writes it gives you a streak, I heard that you could use Events to check if the block is still in the area.
Which event is that?
why not using sprites
idk what event means in this context, it can be anything lol
When you say events, I assume you mean physics messages
Like OnTriggerEnter and OnTriggerExit
Or just OnTriggerStay would be good enough I guess
Those will need colliders, so you'd want to use sprites as nav said
I have to use the canvas to make the game (Design wise Resposive)
Well then you're gonna need to just track positions manually
And It's so tricky to do that, the Rect Transform behave strangely
yeah because you wouldn't want to use canvas for this type of gameplay
What I ment By Events is like IPointerEnterHandler (Interfaces)
that only tells you if your pointer interacts with UI but not like a keypress
Man building your game out of UI is just going to be a bad time
Anyway a proper rhythm game doesn't depend on the visual representation of the objects anyway
made a whole game with Cards in UI and let me tell ya thats hard as it is, i can't imagine something you need movement.
the thing the player sees is just a presentation layer
the best way to do the gameplay is purely in the data model
e.g. you know the note is coming at time n, then it's valid to press the key at n +/- .05
Is there another way to appropriately scale the game with screen size rather than canvas?
the notes on screen are just a visual representation of that
there is a script somewhere that shrinks/expands sprites according to screensize
I just know there's a Canvas scale section that help me with that. idk if there's another
no built in ways for sprite renderer
https://www.google.com/search?q=scale+sprites+with+screensize+unity
Can someone help me disable this popup. It shows up in visual studio code when I do literally anything to chage my code, even adding a space. I have tried enabling these settings but none of them stop the popup.
I've been working for a month on it, and it's completly uses UI elemnts 😬 .
Thx anyway, I'll see if I have time to replace it
Hey guys, I've successfully included Unity.Collections as an assembly definition reference and now I can use collections such as the NativeHashSet. However, I still can't use NativeParallelHashSet... how come?
What happens when you try?
What does your code look like?
What version of Collections are you using?
Hi! I need help please!
So, this is my character roster
whenever I press Shift, the present character gets disabled and I control another one
The usual "CS0246 The type or namespace name 'NativeParallelHashSet<>' could not be found (are you missing a using directive or an assembly reference?)".
Unity 2022 LTS, fresh project with the latest Unity.Collections version of 1.2.4.
public class NewBehaviourScript : MonoBehaviour
{
NativeHashSet<int> nativeHashSet;
NativeParallelHashSet<int> nativeParallelHashSet;
}
its all fine except for the animations
that version of Collections does not include that type
NativeParallelHashSet doesn't exist in 1.2.4
That's actually a pretty old version.
when I change controls while running the disabled script character keeps doing the run anim
The latest version of Collections is version 2.4
It kinda depends which Unity version you're using though
Wait what? I don't see an upgrade button in the package manager o.o
What Unity version are you using?
No, I shouldn't have!
How can I upgrade the package then? (without an update button)
Sometimes the upgrade button isn't there because the package is locked
Maybe it has to do with my dependencies
it might be locked due to compatibility for another package you have
for example Jobs
or something else
may be yes
Alright, thank you very much! You guys were super helpful 😊
We almost forgot about Mclovin!
What are you using to move to the run animation? Activating a animator boolean? In that case, you might have to turn if off when you switch characters.
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.
I'm pretty sure you'd be better off using animator parameters and setting those to true/false instead of calling Animator.Play(stateName)
Also don't cross-post
#💻┃code-beginner
oops! sorry
private void OnValidate()
{
int count = m_interactionActions.Length;
for (int i = 0; i < count; ++i)
{
m_interactionActions[i] ??= new NoAction(EInteractionType.None);
if (m_interactionActions[i].TryGetActionBySelectedType(out InteractionAction interactionAction))
{
m_interactionActions[i] = interactionAction;
}
}
}
I'm trying to figure out the SerializeReference attribute
For some reason it doesn't display my enums correctly in the inspector
It does display correctly after I edit the array tho
Sometimes it works fine, sometimes it doesn't, honestly I have no idea what exactly makes it behave this way
enums are buggy in the editor in general if you don't map the first element to a zero value
From what I can see so far, it happens when I close and re-open the inspector for that specific GameObject
not sure why that is but it's an annoyance when working with flags sometimes
Added via button, the enum displays correctly, when edited it turns into an int
when adding another element, it displays correctly again, until I change it again
They all start at zero
Is there a way to manually refresh the inspector window?
Closing and re-opening the inspector makes the enums display properly again, so that might help
Oh, by manually I meant via code
you can set the version in manifest.json
I removed the packages that needed that specific version of Unity.Collections (I didn't need them). Then I could update it :)
Documentation question - My team and I are finishing our C# SDK API and want to make documentation for it. It's all well commented, but just need a way to quickly turn the commented code into documentation.
Any tools out there to easily generate documentation from well-commented C# code?
I'm experimenting with DocFX myself
Here's an example of the output of DocFX: https://dotnet.github.io/docfx/api/Docfx.html (this is the docfx api itself)
Jet brains ai works pretty well. I believe it's out of preview. 10 a month roughly. They need to join their AI with their new writerside product. It's a technical documentation product with markup.
where is the completed games thread?
Everything got consolidated into #1180170818983051344
oh, discord is getting messier nowadays
Im not familiar with whats going on its supposed to cut into the wall but it doesnt do that.
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.
but who cares i'm a game developer, what could be worse
stop listening to GPT and learn how to do it lol
i think you should make not make it destroy the game object until your objective reached from A to B
i actually don't think you should implement destroy game object at all
ooh
more like split it
what prevents it from instantly splitting?
laser cutting objects seems too advanced idk what is your objective
a stupid home project