#archived-code-general
1 messages ยท Page 312 of 1
oh that's simple
void UpdateUI() {
for (int i = 0; i < maxDashCount; i++) {
DashUiElements[i].SetActive(dashes >= i);
}
}``` Something like this. Just call it whenever `dashes` changes.
it assumes you put the images in an array or list called DashUiElements
which you should
DashUiElementsthis would a object ?
it would be an array, as I just mentioned
public Array DashUiElements; like this ?
arrays are op i was trying to do the samething i completlety forgot about arrays THANK YOU
how do i set a ui toggle to array to a string i trieed public toggle[] whateverthetogglenameis
huh why do you need string?
"how to define here ?"[] DashUiElements = (DashChance1, DashChance2);
pretty much any object can be an array
hi, i have a character jumping in the editor but not when i build and im not sure if its to do with my code or not but i suspect it is
` private void Update()
{
if (horizontalInput > 0.01f)
transform.localScale = new Vector2(-0.5f, 0.5f);
else if (horizontalInput < -0.01f)
transform.localScale = new Vector2(0.5f, 0.5f);
anim.SetBool("run", horizontalInput != 0);
if (CrossPlatformInputManager.GetButtonDown("Jump") && isGrounded)
Jump();
if (Input.GetKey(KeyCode.Space) && isGrounded)
Jump();
}
void Jump()
{
body.velocity = new Vector2(body.velocity.x, speed);
isGrounded = false;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
isGrounded = true;
} `
my jump code
why is this happening the cooldown works once then it just gives me infinite dashes
and i want my button to change the interactable function not visibility
!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.
send ur code from here
use link
when i DashChance[i].SetActive( dashes >= i ); keep the dashChance a toggle setactive dosent work and when i put IsInteractable it still dosent work can anyone help
what are you trying to do exactly?
Basic C# syntax errors.
what should i do?
but my ui button works from interactable i dont want it to be setactive
and some of you code have problems after 2 times dash i get infinte dash with no cooldown
This isn't how you set whether a selectable is interactable
Didn't you have code doing it before? Why are you suddenly trying to use a different function
You'd have to show your code
here is video of editor and then of build, in both i press space and for some reason it wont work in either my ios build or my windows build but it works perfectly fine in the editor, cant find anything online as to why this is happening
Without seeing code nobody can really help. My guess would be framerate dependent code though, or reading input in FixedUpdate or something along those lines
You tell me, is it working?
i kept all the jump input out of fixedupdate, i only included the movement stuff in there and thats working fine
now its not working at all ๐คฃ
Hi all, I was wondering if anyone's familiar with Unity's ML Agents. I am trying to use ML Agents to play flappy bird, but my code doesn't seem to function correctly. I can't get the neural network to learn. If anyone can help, that would be much appreciated.
tried copy pasting code in and out of fixed update which did nothin
i fixed it
i just closed and reopened editor LMAO
Why does my player move slower on slopes?
I also lose speed whenever I collide with a slope
i mean isn't that how physics work
i would like for it not to be
i thought setting drag to 0 would fix it - it didnt
maybe use kinematic or character controller.
doesn't work for the type of project / movement i'm working on :)
do you know why the bottom line of code doesn't fix things?
is there a video online video that shows rb based controller fix for slopes?
i've looked for some - can't find any that work
you probably need to manually correct the velocity based no slope angle
thought the bottom line of code would fix that - why doesn't it work?
I wouldn't rely on that , i would at very least use a raycast
not sure what you mean
OnCollision enter only happens once
OnCollisionStay?
at very least.. or just a sphere cast for example if player is capsule, to get more area/width
how would you suggest i use a spherecast?
spherecast down to detect the slopes
if it detects a slope, what should it do
correct the velocity accordingly
thanks, I'll send a message there
Github related
Can someone please point me in the right direction!
What files from my unity project should i be pushing to git?
there's various premade .gitignore files you can find for unity, but for starters you can usually ignore all the folders except Assets, Packages and ProjectSettings, and all the project/solution files
One last question! and thank you for your response!
I had tried pushing the ProjectSettings folder earlier lastnight and it kept failing because the file was bigger than github allows, is there a specific way around this or will i just not be able to upload the ProjectSettings?
what on earth is in there? it should be a few small text files
lemme go see
should there be a packages folder be inside of the ProjectSettings folder?
yeah, that just has package specific config files
hmm im not seeing anything of a high file size within the ProjectSettings that would have stopped it , Maybe it was because i had tried commiting the Library folder with the ProjectSettings folder and thats why i got the file too big error
oh that's more likely
if you have previously committed library/temp/bin folders you may want to revert those commits so they don't exist in your git history, they can make your repo huge even if you're not using them
Thank you for helping me out!
I think ill go make a new repo and start from the beginning again!
If i use one of the .gitignore templates does that tell it to automatically filter out only what i would want from the project?
yeah, there's ones with all the common unity folders set up for you
https://github.com/github/gitignore/blob/main/Unity.gitignore this one (first one off google) looks fine to me
Thank you!
Ill go mess around with it , see if i cant get it working this time lol , i probably messed around with it lastnight for 5 hours and kept running into the same issues.
I mean like this. At the blue mark the player will start to follow the spline red is the path it goes on and the yellow and purple marks are the points if the player jumps that the z position gets pointed there and the green mark ends the spline path allowing the player to go back to free motion, The one in the middle is more of knowing which side he on now.
!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.
Can anyone help me with what may be the problem? I don't understand how that is the problem considering the name of my player console and first person controller is seraph. Anyone got any ideas on how to fix it? I was trying to implement a pick up system for some letters.
You don't have a class named seraph
The names of your GameObjects are irrelevant for code
Appreciate it my bad.
So you need to configure your IDE
I want this shader to have a circular zone around the player that is normal while things farther away are distorted. I've been stuck on this for a couple days now.
currently everything is distorted, which is 50% there
Pass the player's screen space position into the shader then only apply the distortion effect of the distance is less than some radius. Use the step function
dope ill try that, thank you
How doable is a perk system in a multiplayer game? These perks are unlockable and the players can use these perks in any server they join
bear in mind I am quite a beginner, this is my first game
beginner
multiplayer game
these things are not compatible
i mean is it really that hard? its an idea I cant get out of my system
yes, start by learning what you are doing first before diving into your "dream game" or whatever. learn how the engine works, learn how to make a game. once you have that experience you will still struggle with multiplayer, but at least you'll understand what you are doing and why you are struggling
i am not really lost to be honest, I have used the engine before but I have just not made a game before
so far I have made things that are not really easy
how doable is it? completely
will you be able to do it given your skill set is another question.
I have just not made a game before
so you do not have the experience needed to understand how to architect your game in a way that will make multiplayer not an absolute nightmare
you can give it a shot if you are really dead set on it, but expect to fail. or at the very least expect to not have made the game you are envisioning.
understanding how to create your game and how to network it is a huge undertaking
I will give it a shot, I think I am deep enough that I cant go back now
I'll see where it takes me and I dont really care if it succeeds or not, I just want to try
also consider the fact that you asked about a perk system. Something that at the end of the day equates to adding 2 floats together, or even just simply running a method which contains the perk. The rest of your game is definitely gonna be questionable
I dunno, some trigger on the ground in front of it? Does it need to be a spline for that anyway?
well so far I have made an inventory system and a functional crafting system.
they work just as expected
If there a way to around that loop without it being very werid then yes
if the perk system is easier then oh well
I was just asking about the multiplayer part of it
What about the multiplayer part of your inventory and crafting systems?
There are many ways to do everything
is there a reason that IPointerExit isnt called when an object is destroyed? how do I cause that to happen?
Plus based on sonic superstars it ises a spline system
no I meant the perk system. Not these two
Then cool, seems reasonable
If you havent started the multiplayer part, you surely arent deep enough that you cant go back. Unless you signed some contract on doing this ๐
So these two are not gonna work in the multiplayer mode?
But Iโm asking how it can be done
they will
Well, did you implement the multiplayer part then?
you guys talk like multiplayer is the final boss, what am I going up against lol
it is much harder to tack on multiplayer after the fact. if you have not been building your game in a way that would be friendly to multiplayer then you are going to have a very bad time
no I still haven't
Ah, multiplayer... I am on my 4th rewrite of my multiplayer code so far, even with pretty good architecture, its still a big challenge to optimize net code and gameplay, and we havnt even gotten to security management yet
Then maybe do that before implementing other systems, but really I agree with the rest of the people that you should start sorry a single player.
๐คทโโ๏ธ i hope you realize determination alone isnt enough to build a rocket ship.
Just saying, i had 9 years of coding experience and started with a mutliplayer game as my first project. I ditched it because it was too much.
OnDestroy => IPointerExit(new PointerEventData(EventSystem.current));
i'm like 6 months into a multiplayer project and i already know i'm going to have to go back and rewrite a lot of stuff and i already had a lot of experience with making stuff in unity before i started it
I wouldnt ditch it to be honest. When I reach that part and see that this really is a challenge I cannot overcome, I will just leave the project on the side and work with what I learned on something else. I don't plan on giving up on this idea early to be honest as from my perspective I see that its a really unique idea for a game.
I raged at my item looter multiplayer project
making a multiplayer shooter is like 1000 times easier even if you need to deal more with latency
I am confident that this idea in my mind has a chance so I won't go back unless its really like... impossible to me.
will probably tackle that project again eventually but too much databasing for me
but anyways, thank you guys for the heads up. Now I know that it would be normal when I feel like its hard
I sent a video. That is how you follow the spline.
I told you to use a trigger area to initiate following it.
What part do you still need to know?
thanks
when exiting or switching scenes, this causes a bunch of errors
since event system is being destroyed i assume
nvm, its because another object is being destroyed beforehand
It's just an idea that you need to probably set up some callback yourself if IPointerExit doesn't get called. Ideally you should just make a method to be called inside of IPointerExit that you can also call on the outside instead of having to directly access IPointerExit when destroying.
I'm starting to feel alright during my break here
Hey there, I'm trying to link some sfx to a heat ray weapon I've made. on mouse click, it should play the 1st section of the clip once, then loop the 2nd/middle section while mouse button is still pressed. Once the mouse button is released, exit the loop and play 3rd clip where the sound releases & fades away.
Is there a way to do this other than splitting the sound effect into 3 separate files?
You could probably use .time from the Audio Source your playing from, of course, youd have to know the exact point in your audio clip to split those 3 phases
right, I'm designing the sound effects from scratch so I can find where to split it. might use .timeSamples since apparently .time changes according to compression
thanks for the suggestion
How can I make the seperator line "full" with richtext
instead of having gaps between
where is the code question? not sure what ur asking here..
sorry, I'm using string builder to make the description and want to make the hyphens "connected" not sure if that's possible
connected as in a straight solid line?
thats dependening on the font, idk if you can crunch the characters together without making a font variant with that setting and try applying that variance
TMPro supports a lot of tags: https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/manual/RichText.html you could try something like margin, indent, width, etc, or maybe just use underscore _ instead? Or a sprite of a line if you want it stylized
hmm you could try https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/manual/RichTextMonospace.html
maybe and give it a negative val for spacing or really low?
Somewhat related, is there a way to provide rich text to UGUI text/TMP without having to deal with their rich text syntax?
Eg if you already have to do some form of parsing yourself like markdown, it'd be nice to be able to directly convert the AST and supply them, than to do another roundtrip.
Can someone please help me with github?
Ive spent a total of like 11 hours now trying to get it to work but every single time i try to push the project to github which takes like 3 hours it eventually throws an error because its trying to push the Library folder to github , I made sure the repo contained a .gitignore that was set up for unity and still it fails .... please im losing my sanity
delete any old folders like hidden .git or any files related to it, Get Github desktop, use a GUI.
redo the process . takes 3 mins
https://youtu.be/5IxUElilf2M
Thank you!
I will try this!
quick question do i need to push the Packages or the Library folder from my unity project?
nevermind sorry i wasnt following the tutorial , am now
If I understand your question correctly, you can disable rich text formatting, under the "extra settings" tab of the component, or are you asking if you can use custom markdown tags without parsing a second time after TMP has already parsed their tags?
mspace works great, thanks
Yeah, let's say I get input from somewhere where the format isn't TMP/UGUI Text compatible, eg markdown, I have to do markdown string -> markdown AST -> TMP string, which TMP would do its own parsing from TMP string -> TMP AST -> finally displaying stuffs.
If there's a way to hook into the AST directly, I'd get to skip the whole middle step of going back to string, and just convert between the two ASTs. It's especially handy not having to deal with escape rules.
what spawns the player? what spawns the enemies? Likely these scripts are related if not the same GameManager kind of script.
Whatever spawns the player can just keep the reference to them. Then provide it to the enemies whenever you need via some public function.
this is very vague, where do these events live if not on a script? it is bad if you make it bad
I have a savegamemanager. If I load the save data it works. if i leave the scene and come back it breaks and can no longer load. Am I supposed to somehow read all the data into memory and sit on it until I need it? It seems I can only load files once.
Hello! I have a ScriptableObject, called a map, that has data. It has to have a string that links it to a scene, I'd like to automate the creation process of maps by also creating the Scene automatically
I have the path + name set up, but I don't know how to actually make one... so is there a function I could use to create a scene on the ScriptableObject's creation??
Here's what I tried, didn't work... Maybe it'll give you an idea of what I'd like?
EditorSceneManager.SaveScene(EditorSceneManager.NewScene(NewSceneSetup.EmptyScene), path);
could you do it on awake? not sure if awake runs everytime you load the project up but thatd be an easy check if the string is not null.
https://docs.unity3d.com/ScriptReference/ScriptableObject.Awake.html
Oh, yeah of course, just like
I need to create the scene asset, I have no clue how to do that, and I can't find anything online that works
havent done this before but online this comes up https://forum.unity.com/threads/create-scene-asset-from-editor-script.1035340/
Doesn't work...
(I know I used OnValidate, only because OnAwake doesn't work for path reasons)
can I ask one of you a question about learning Unity
{
//Create variables
string nameAsset = name.Replace("Map_", "").Replace(".asset", "");
string path = AssetDatabase.GetAssetPath(this).Replace(name + ".asset", "");
if (_Scene != "")
{
_Scene = "Scene_" + nameAsset;
AssetDatabase.RenameAsset(path + _Scene + ".unity", _Scene + ".unity");
return;
}
var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);
EditorSceneManager.SaveScene(scene, path + "/" + nameAsset);
EditorSceneManager.CloseScene(scene, true);
}```This is what I used
This channel is for helping with general code issues related to Unity. You can !learn using the many free topics online
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Not sure if this is the right place to ask cause its not technically code itself:
I have a question about DataPath and PersitentDataPath:
I do not quite understand the difference between them, from what I understand PersitantDataPath points to some folder like "AppData" while DataPath points to the DataFolder in your game.
I am using DataPath right now for loading in textures for a texture-pack system, that works fine.
Now I wanna implement a save system and it sounds like I should save settings/ saveFiles in PeristantDataPath, but why is DataPath not peristent? Files saved there will not stay after play is over? Why is one "persistent" and the other not?
Hi everyone. Can somebody help me with animation for my dyplome game? It's a basic thing, but I'm a beginner and can't solve my problem. Question in "Artist tools -> animation" branch
it's really quite simple. dataPath does not exist in a built project. streamingAssetsPath and persistentDataPath do. so you should never be using dataPath
It does though? I am using it to read files from there
in the Editor. Have you tried in a build?
https://docs.unity3d.com/ScriptReference/Application-dataPath.html
well im unsure about the above about it existing in a build. but you can see one use case right on the docs
iOS player: <path to player app bundle>/<AppName.app>/Data (this folder is read only, use Application.persistentDataPath to save data).
In engine it points simply to Assets
Ohhh
So I guess the main difference is that its read-only?
That would explain why it works for me, cause the texture-pack is placed in there manually and reading it works
I havent tried writing anything there yet
it may work for a windows build. it will not for an Android or WebGl build
the part i linked is specific to iOS, if you are doing that
So I guess I should use persitentDataPath for my usecase?
Putting a texture pack folder in
And saving settings/ savegame
if you want the texture pack included in the build use streamingAssetsPath
no just for players to add their own if they want
It overwrites any texture in the game if it has the correct name
then persistentDataPath is the way to go
Hi, im trying to figure out how to create a nativeArray from a pointer using NativeArrayUnsafeUtility but all I get is "Object reference not set to an instance of an object" error
NativeArray<int> testArray = new(1, Allocator.Temp);
testArray[0] = 12;
void* pointer = NativeArrayUnsafeUtility.GetUnsafePtr(testArray);
NativeArray<int> recreatedArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>(
pointer, testArray.Length, Allocator.Temp);
Debug.Log(testArray[0]);//12
Debug.Log(recreatedArray[0]);//Object reference not set to an instance of an object
What line throws the error?
The last debug log?
Yes
Thanks, I just had to add a safety handle
If i have a string (e.g Something is <b>blue</b>) and I want to remove <b> and </b>. Is regex.replace more performant than doing a loop thru a stringbuilder and then remove the substrings by hand?
Regex will always be worse, but nowadays Regex can be code generated although I doubt Unity supports it
But if you strictly want to remove <b> or </b>, why not use a regular string.Replace?
@versed loom
String.replace really should be fine and faster which is something you literally only notice if doing 1 million times in a single frame
Do you do this often or is this just once?
once
If you do this once you can also just use a Regex
and in an editor script
But in the same way just iterating a string and looking for the characters to remove isn't that hard either
yea true
Either way this would be the regex https://regex101.com/r/jDPLR8/1
If your tags contain multiple characters add + after the w
thanks ๐
I'm tinkering with sprites and I was wondering
I have an atlas and I've sliced the sprites so now there's a bunch of sub-sprites
How can I through code get the UV coordinates of the subsprite on the atlas
There's the UV property but it's an array of vector2s
This is kind of what I want but I want it to range from 0 to 1 (1 = very right 0 is very left)
Wait I suppose I could potentially divide the x by the width and the y by the height
Indeed and that will give you the same thing as the first Vector2 in the UV array
Ffs lmao thanks
so... i want to make a script that gets the average normal direction of the ground in a sperical area around my player.. im aware you can access all normals of the mesh you've accesed via raycast & use the world position of the normal to determine if its within range, however, this would have to loop through all the normals on the mesh each frame, and that doesnt seem very smart resource wise. is there a way to simply get all faces within an area regardless of face orientation or parent mesh?
loop through the normals on the mesh each frame
hi everyone, can someone help me with climbing wall in 2d platformer. I know this sounds pretty basics but I want to add velocity to player when they are climbing using 'W' and 'S', and subtract an amount of velocity from player when they're stop pressing buttons. I dont want Stop Climb to set vertical velocity to 0 as it is negating all other forces including jumping. I have tried adding a variable that keeps the lastVerticalVelocity applied, however when the the player is hitting against wall, their velocity is now 0, and the lastVerticalVelocity isn't correct anymore. Is there anyway to achieve this wall climbing mechanics?
Do a fixed number of Raycast samples in a sphere around your player and average the normals you see
I haven't seen a tutorial that makes wall climbing without setting velocity to 0 on stop
Anyone has made modding avaible in their game? Not just adding new visuals to the game or adding new assets more llike adding plugins and new levels or enemies if anyone as can I send ask some questions
i would do this, however there are some cases where faces (due to their orientation & the ray origin) would be impossible for a ray to hit, which in turn doesnt result in the result being true to the average face orientation within the circle
Ignore those in the average calculation
Or also try the inverse ray when there's no hit
this could work actually... thanks!
!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.
https://paste.ofcode.org/vBFsnZ4nPeWq8nMPq4pQzL
What I do wrong? I have blend tree correct transition between walk and idle. I writed to set speed related to Velocity. But when he came to gizmo he continue walking.
Any help much appreciated, heading into work now but will read after. @cosmic rain sorry for the ping but if you get a spare moment today youve been really helpful and I appreciate the help
what do you mean it breaks? is there an error message?
ya got a lot of stuff going there, why dont you break it down for us and tell us what part is breaking
Im heading into work rn, probably should have waited to bump this. Basically I have objects that use the load method and it works great. If i leave the scene then come back it errors out even tho it was perfect the first time. I think it was saying filePath is null. Ill have to look again after work. Thanks
I was thinking of removing .dat from the files to make it all easier.
you should at least move the line which appends .dat before loading into the save manager, at the moment you have it expecting a plain scene name in SaveLevelData and a scene file name with the .dat extension in LoadLevelData, which is really confusing!
but it's hard to say what else is going wrong without seeing the error/logs
- Don't ping people into your questions.
- Share your !code correctly.
- Share the details of the issue correctly. If you were getting an error, share the error details.
๐ 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.
Hi, please ask this in #๐ฑโmobile
oh okay
And you were told where to post, which was not here
Active channel != correct channel ๐
okay question gone, took me 2 hours to code and debug this climb thing
never adding it to my future game
Ok, next time you want to buy a pair of shoes and the shoe shop is busy/closed, go next door to the butchers
Can ya maybe help me in the #๐ฑโmobile thing?
No, I don't do mobile stuff. This is one of the reasons why channels are divided
oh okay my bad
Is there a straight forward way to showcase 3D items (gameObject) set in code or inspector in the scene view ? Currently I have a OnDrawGizmos in use , but the children down the line do not get wireframed unlike the parent. (Tried protected on parent and sending it from children and also a function that would change it seperately )
It's confusing what you're talking about. You said "I have a OnDrawGizmos in use" but that's very vague
And you seem to be mixing up parent and child GameObjects with parent and child classes in C#
Sorry, yes so the parent is lets say Item and then child is Tool : Item , but then the Item gameObject could be one mesh while the Tool is assembled together by two pieces. So im sending the assembled piece to parent so it could be rendered right . But it doesnt get sent to the OnDrawGizmos before i press start.
[SerializeField]
protected GameObject itemModel; // The 3D model of the item
void OnDrawGizmos()
{
if (itemModel != null)
{ // ColourByTag script in Utilities
Gizmos.color = ColorUtility.Instance.GetColorByTag("item"); // Choose a visible color
Gizmos.DrawWireMesh(
itemModel.GetComponent<MeshFilter>().sharedMesh,
transform.position,
transform.rotation,
transform.lossyScale * scale
);
}
}
And for test i tried in the child this way at the moment (tried start too)
private void Reset() // Called in the editor when the component is added
{
if (itemModel == null)
{
itemModel = Instantiate(toolModel, transform.position, transform.rotation, transform);
itemModel.transform.localScale = Vector3.one;
}
}
i want to add characters in unity and when in first person you can see your hands/body. and id its multiplayer i want others to see my character aswell. can someone tell me how or send me a video on how to do this
https://github.com/spriest487/spacetrader-utils/blob/master/GameObjectGizmosUtility.cs here's a method i use to draw gizmos for an object and all its children, is that what you want?
Contribute to spriest487/spacetrader-utils development by creating an account on GitHub.
Thats looking alot like what i was imagining yeah, didnt really think about taking it apart into a seperate utility.
for gizmos I usually just have some manager singleton with a single draw method and let all my objects access that instead
can anyone explain why my Dash() is never being called ?
https://gdl.space/axojivumum.cpp
need help to create a good fnaf NavMesh AI (dm for more details if you want to help me)
How about sending the entire code so we can see the full context of how the code is being executed.
i'm assuming you start with max dashes? your Dash() call is inside if (dashes < maxDashCount)
Also if (dashes < maxDashCount) is most likely causing the issue. it should be only wrapped around the first inner if statement (timer)
what do you mean
yes
private void Update()
{
if (dashes < maxDashCount)
{
timer += Time.deltaTime;
if (timer > cooldownTime)
{
dashes += 1;
timer -= cooldownTime;
}
}
if (Input.GetKeyDown(DashKey) && dashes > 0)
{
dashes -= 1;
UpdateUI();
Debug.Log(dashes);
Dash();
}
...
}```
There's only a reason for the timer to be updated if your current dash count is lower than the max count allowed
so how do i wrap it ?
Literally the way I just did.
Why is:
if (Input.GetKeyDown(DashKey) && dashes > 0)
{
dashes -= 1;
UpdateUI();
Debug.Log(dashes);
Dash();
}```
inside the other if statement?
I don't think that's how I had it in my sample code I shared with you yesterday
If anyone here knows how to work with unitys NavMesh system and can help me make a good fnaf animatronic ai then please dm me (I got some code ready)
Yeah it's not
i just realised how dumb i am
in fact you put almost all of your functions inside Update @solar wigeon
you screwed up all the brackets basically
this is very vague. I have no idea which script this is.
it's unclear what you mean by "sending it to the parent"
sorry a dumb mistake still quite new to programming
anybody know how to solve this?
can u guys tell how to implemet ui as an array
https://gdl.space/enelahesed.cpp
DashChance[i].SetActive(dashes >= i); except of being SetActive i want it to be IsInteractable
We went over this yesterday too
Remember your old code where you were setting interactable = true or false
you do it that way
You need to have an array of Image or Selectable though if you want that
Like you had before
oh ok ๐
is there a way to get a pixel of a rendertexture from a mouse click?
Please, consider not cross-posting. Yes, #archived-code-general should be a nice place for this question
wait- what's cross-posting?
You should take a look at the Texture2D.GetPixel method and this question on Unity's forum
Posting the same question on multiple channels, in this case.
https://www.google.com/search?q=cross-posting
ahh
sorry-
I saw that a discussion was already going on in unity talk after I had posted it
and then I thought maybe code-general would be a better place
I'll go delete that comment in unity talk :D
Yes, consider deleting it in order not to have your question being answered on 2 different channels, as they probably aren't going to redirect you, because #๐ปโunity-talk is also suitable for your question
done!
yeah makes sense I guess xD anyway, i don't really know how to use texture2d.getpixel with a rendertexture...
oh lol
How do I select a spriteโs pixel by mouse click?
That's why I have also sent you similar question on Unity's forum
Implement it. If there's something you don't understand about it or the answer doesn't fully achieve your objective, ask an another question here.
ok...
so what I've got is a compute shader running conway's game of life on a render texture, and I would like to have the ability to make cells that I click on become alive.
Yeah, so it's very similar to the question on the link I've provided
alright :/ I'm sure I can figure it out
And I'm sure you can achieve that using that link.
And, please, consider googling your question before asking it here, as there is a plenty of questions with the answers on the web already.
https://www.google.com/search?q=unity+get+pixel+from+mouse+click
yeah that's the thing- I did xD I just thought I was looking at the wrong things
anyway, thanks!
Is there a way to mask 3d objects with a 2d image without a shader?
I have a grid of objects in a scrollrect and they peek out of the scrollrect bounds
Maybe render your 3D objects with a RenderTexture?
Then it will be masked normally with UI mask
as its for mobile i want to prevent additional cameras
I doubt you'll be able to do something without a custom shader then
I've got a button that swaps out with another button when it's pressed, and vice versa. But when I press it, both buttons get activated, as if I tapped it twice. This doesn't happen when the buttons aren't overlapping. Any thoughts?
I only click it once at a time there until the end where I spam it
Mm, maybe consider changing the button's sprite..?
Although not sure whether it's the most appropriate solution
Also, that's a normal button, right? It should be pressed when the button is released, which shouldn't activate the 2nd button.
Could you perhaps provide more context how you activate them?
sounds like both buttons are getting clicked.. what do you do with the "swapped out" button?
I like @gray mural 's idea of changing the sprite tho- avoid that kinda "both get clicked" stuff all together.
!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.
Hey all, been working on this problem all morning and figured Id see if anyone had any advice for me
So I'm realizing I made a slight mistake in my use of Scriptable Objects for the design I'm going for xP
basically I have an abstract class SpellSO, and things like ProjectileSpellSO and BarrierSpellSO that inherit from it, and I put the logic for casting the spells into that, hooking it up to my players SpellManager. This works perfectly fine if it was only the player casting these spells, since the player would be the only one accessing any of the functions in the scriptable objects.
but my plan is to let my EnemySpellManager hold the exact same spells to cast, which means things like castPerSecond start getting shared between my player and the enemies. tbh its kind of hilarious and might make a fun mechanic, but for now its something I need to fix.
I was planning to change the spell SOs to pure data containers for things like the prefab or any numbers it needs like damage and mp cost, and then move all the methods in those SO's to the SpellManagers, but I wanted to see if there was a better way to handle it
definitely let your SOs be pure data containers
It's also unclear what benefit you get from inheritance here
ProjectileSpellSO what's better about this vs just having a SpellType enum on the SpellSO?
If you get rid of inheritance it becomes much easier to manage the actual SO assets in your assets folder
right now I have 2 types, Projectile and Barrier. the base SpellSO has basics like mpCost and spellName, with abstract methods for the CastPressed() CastReleased(), while the individuals are holding the specifics like projectileSpeed or barrierDuration that the others wouldnt have a use for, as well as implementing their own CastPressed or CastReleased stuff
plan is to add more like MartialSpells, SupportSpells, so this was how it made sense for me to break it up xP I'm new to this so Im sure it needs work
I mean I guess I could use an enum, and then switch states under the CastPressed etc, is that the suggestion?
How do i go about diong gpu instancing for this?
Hey, could anyone help me figure out how to create an empty scene and save it to the assets folder? Its for a ScriptableObject
Did someone @ me?
Yeah, I did, I realized you probably meant by code
Yes, when I create a new ScriptableObject, I'd like to automatically create a scene, pair it with the ScriptableObject, and save it to the assets
Uh, is there a way to use this method to create a completely empty scene?
I took a second look.
This may be better
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.CreateScene.html
Create an empty new Scene at runtime with the given name.
It needs to be in the editor, I've also already tried this
the open scenes need to all be saved in order to create a new scene
or rather, there cannot already be an untitled/unsaved scene
Thing is they're all saved is the issue
including the one you just created?
No? Hmm
{
for (int x = 0; x < size; x++)
{
float rngTree = UnityEngine.Random.Range(0f, range);
worldX = meshPosition.x + x;
worldZ = meshPosition.z + y;
if (treeNoise[x, y] < UnityEngine.Random.Range(0f, 0.5f))
{
if (heightMap[x, y] > 5)
{
Vector3 pos = new Vector3(worldX, heightMap[x, y], worldZ);
Quaternion rot = Quaternion.identity;
Vector3 scale = Vector3.one * 1;
matrices.Add(Matrix4x4.TRS(pos, rot, scale));
index++;
}
}
if (treeNoise[x, y] < rngTree)
{
if (heightMap[x,y] > 5) {
GameObject newTree = Instantiate(treePrefab, new Vector3(worldX, heightMap[x,y], worldZ), Quaternion.identity);
newTree.transform.parent = treesChunk.transform;
}
}
}
}
Graphics.DrawMeshInstanced(grassMesh, 0, grassMaterial, matrices);```
im trying to do gpu instancing for grass
however it wont show?
i saw somwhere that u had to chekc the gpu instancing
i did do that but it doesnt help
what did you do? save over the scene you were already working on with one of your new empty scenes?
if that is the case, surely you have some sort of version control so you can just revert the change, right?
No
I don't
I'm fucked
It accidently overwrote
Everything
All my maps
It created new scenes
And just
Saved over them
There's no way to revert this is there
I have a built version a few days ago
I could revert the build, yeah?
I could get the scenes from the build
I would lose progress, sure, but it's better than losing everything
well let this be a lesson to always use version control
and if it is possible to get the entire scenes from your build, it would be done using tools that are not allowed to be discussed here because it is against server rules to discuss decompiling or asset ripping
not a code question. see the documentation pinned in #๐ฒโui-ux to learn how to anchor and scale your UI
I already use git, but nothing for like
Maybe a few weeks
But too much stuff would be lost regardless
A new level, a new city-
Then count yourself lucky you have something from at least that far back and the lesson becomes "Commit more often"
When I mean everything, I mean everything
and definitely before doing something potentially destructive
Since weโre talking about this How do I put on version control :?
Im making a big project so yeah I uhhh donโt wanna demolish this accidentally
๐ญ
There are many tutorials setting up git with unity. Then get yourself a GUI like github desktop so you dont need to use terminal for the commands
Hello I currently am implementing combat animations into my game and have the input working for a punch attack but when my animation is transitioning back to the idle state my character just gets stuck on the last frame of my punch attack and can not go back to the idle state. I keep trying to reset the trigger code for my animation back to false after it is turned on but it wont. any advice?
Swag
I have github desktop, I tried using git LFS but couldnโt figure it out, Iโll try it again
Iโve only done vscode things on github but unity files are like massive
anyone kinow what could be causing this? When I click on the text, i doesn't take me to the file where the issue is located so I have no clue what's going on
nothing seems to be broken though, just keep getting the error
You dont need lfs unless you have some massive assets I believe. Did you properly setup the gitignore? You're not supposed to push stuff like the library folder
Do you have the same name for some variables in a base and child class? Both being serialized causes it
Uhh I donโt remember, let me try again I removed the git stuff a while ago when I couldnโt figure it out
dont think so, im using new to override the base class variable
Anyway guys if I happen to make like a really big switch statement will that like be bad for performance or something or will it not matter I canโt think of anything more efficient for this thing Iโm doing
This is probably the issue from it trying to serialize both. Both exist
what do you mean? If I use new to override then it shouldn't have that issue?
also I do the same for other derived classes and have no issue
new is just hiding the variable, not overriding
are the other classes doing this on teh same variable? it only matters because both are serialized with the same name
yes
i use "new" so I dont have to cast the variable every time
new just allows you to create another separate variable of the same name and just hides the base class's variable of that name
without seeing the exact setup i cant really say why it works in some case. you can see here though both variables do exist https://dotnetfiddle.net/l7TDIr
and are separate
ah i see
should I just remove it and cast instead?
for context, it is my item system
so say I have an equipmentInstance, it references some baseItem SO equipment
the point of overriding is so you dont need to cast, though maybe i am misunderstanding what you're doing
ItemInstance has baseItem with type Item, EquipmentInstance has baseItem with type Equipment etc
and Equipment is derived from Item
"for this thing Iโm doing" describe the use case and itll be possible for people to suggest better things. If you have to ask about it being bad, you know its likely pretty bad
say I have an equipmentInstance, i would have to cast the baseItem since it would be of type Item
I got a problem, but first here's the context:
I recently implemented these things in my Unity project:
-
Scriptable objects that holds information about the GameObject they're attached to ("attached" as: in variables on another script already on the gameobjects)
-
A public abstract superclass "ClassResource" that doesn't derive from MonoBehaviour:
This class is supposed to hold the base information every scriptable object is supposed to have, i.e strings holding the descriptions -
Public subclasses that derive from the superclass:
One example of a subclass is "ClassCraftable", this class will hold info such as the recipe for how to craft the object. It's a subclass since not all objects are supposed to be craftable. But those that are will have both the base info (from the superclass "ClassResource") and the crafting info (from the subclass, in this case "ClassCraftable").
Now, my problem is with the scriptable objects:
I have a public variable of type ClassResource (the superclass) in the scriptable object script and this variable is supposed to hold whatever subclass I decide the scriptable object should "be", like maybe a craftable resource (in that case I'd choose the ClassCraftable script).
And this works, except for in the inspector. The field shows up on the scriptable objects, but when I open the selection window, by clicking the circle with a dot, nothing shows up (and I can't drag-and-drop the scripts either). I want to see the subclass scripts there, like the "ClassCraftable" script, or at least be able to drag-and-drop.
Is it possible or do I have to make like an if-statement with else-ifs for every subclass manually?
(I'd guess it has to do with the fact that the subclasses aren't connected to any Gameobjects or something along those lines)
(I hope this is clear enough. Just felt that context was needed)
Well Iโm asking if large switch statements in general are bad in performance or donโt have an effect. Also I think the point of someone asking if itโs bad is because they donโt know whether it is or not lmfao.
But anyway, Iโm making multiple different methods that are abilities in a turn-based combat kinda system, and Iโm planning on using a list of strings to mix and match the abilities each character has. So like you pick out one of the strings and then itโll run the switch and run the method corresponding to the ability.
If thereโs a better thing to use Iโm curious about it, but if itโs not super detrimental to performance, then Iโll probably just go with that plan anyway
Just asking if large switch statements are bad in general is unanswerable
Itโs not like Iโm a triple A studio or something so not having maximum possible efficiency isnโt gonna kill me but learning different approaches is still cool if you or someone else has a suggestion
Okay ๐
For your use case, consider a dictionary and just get the string as a key, with the ability as the value
The ability would have its own method to run
no switch statements are not bad for performance unless youre repeating code
Oooh okay cool
Thanks!
repeating and expensive calls are the key to bad performance
Okay then yeah I think a switch statement will be fine because itโs a thing that runs exactly once each time you use it, but Iโll try out the dictionary too!
i have this code and all im trying to do is place a 2dBoxCollider (floatingObject) within another 2DBoxCollider called areaCollider. Im trying to make it so that the blocks i place have to be fully enclosed in this collider in order to return true. Can anyone please help me out?
Instead of trying to use Bounds, which won't work if either object rotates at all, you could just place empty GameObjects at each corner and use their positions
ill try that
If my "post" is unclear just tell me.
I gtg now though, I'll look at any replies tomorrow.
I'm not really too good with imagining a structure based on the description. Showing code would be a lot more understandable
It seems to me you're asking about serializing the Type and choosing a child class in inspector which isnt something unity has by default. You would need a custom inspector for it
Although it does sound odd what you are doing with this ClassResource. Best if you show the code. Is ClassResource a scriptable object itself? Otherwise it shouldnt even have a drag and drop area
I have a savegamemanager object that persists through every scene as a dont destroy singleton thing. It needs to be passed as a parameter to an object after the first scene, but its not in my hierarchy. How do I pass it?
there's lots of ways, where are you calling the method that needs it as a parameter?
public class LevelSelectScreen : MonoBehaviour
{
public GameObject buttonPrefab;
public Transform buttonContainer;
public SaveGameManager saveGameManager; // Reference to the SaveGameManager
void Start()
{
if (saveGameManager == null)
{
Debug.LogError("SaveGameManager reference is missing!");
return;
}```
alright well that's a field not a parameter ๐
if it's already a singleton, the easy way is to either add a static Instance property to the singleton you can look it up from, or just to do FindObjectOfType since you know it's in the scene already
I have the instance property on it, I'm not exactly sure what to do with it tho
Question: Is there some obvious way I am missing to search for objects inside a specific scene? This is in the context of stacked scenes for a networked game, but the question applies to additive scenes as well. Nearest I can tell, you have to do a FindObjectsOfType or similar which returns results across all scenes, then filter the results out. Seems inefficient especially if you have several copies of the same scene open server-side.
if it's always initialized before LevelSelectScreen, make saveGameManager private so you don't set it in editor, and put saveGameManager = SaveGameManager.Instance at the top of Start
You can get the root game objects of a particular scene with
https://docs.unity3d.com/ScriptReference/SceneManagement.Scene.GetRootGameObjects.html
And then use GetComponentInChildren or manually recurse through them manually.
sounds like this is what you need! https://docs.unity3d.com/ScriptReference/SceneManagement.Scene.GetRootGameObjects.html
I win ๐
And that will be scoped only to the scene of the object which calls it?
it's an instance method, you can get the scene of a specific object with gameObject.scene and call it from there
so yes, it's only the root objects from that scene
saveGameManager = SaveGameManager.instance;
'SaveGameManager.instance' is inaccessible due to its protection level
public class SaveGameManager : MonoBehaviour
{
private static SaveGameManager instance;
private string savePath;
private const string encryptionKeyPlayerPrefsKey = "EncryptionKey";
private string encryptionKey;
public double totalOverallTime;
public int levelsCleared;
private void Awake()
{
// Singleton pattern
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
instance = this;
DontDestroyOnLoad(gameObject);```
you could just make instance public, but i'd suggest making a public property so other script can't accidentally set it, like public static SaveGameManager Instance => instance;
Thank you (and @late lion ) - I'll check that out!
public static SaveGameManager Instance => Instance;
StackOverflowException: The requested operation caused a stack overflow.
SaveGameManager.get_Instance () (at Assets/Scripts/SaveGameManager.cs:10)
SaveGameManager.get_Instance () (at Assets/Scripts/SaveGameManager.cs:10)
SaveGameManager.get_Instance () (at Assets/Scripts/SaveGameManager.cs:10)
SaveGameManager.get_Instance () (at Assets/Scripts/SaveGameManager.cs:10)
SaveGameManager.get_Instance () (at Assets/Scripts/SaveGameManager.cs:10)
Lower-case i
You're self-referencing Instance, causing an infinite loop
public static SaveGameManager Instance => instance;
it won't let me, says it doesn't exist. Do I just need to state it just above this one?
add this to the existing class, don't delete the old instance
public class SaveGameManager : MonoBehaviour
{
public static SaveGameManager Instance => instance;
private string savePath;
private const string encryptionKeyPlayerPrefsKey = "EncryptionKey";
private string encryptionKey;
public double totalOverallTime;
public int levelsCleared;
private void Awake()
{
DontDestroyOnLoad(gameObject);```
The name 'instance' does not exist in the current context
you deleted instance, put it back ๐
it was there in the last snippet
or if you want it in one line, use public static SaveGameManager Instance { get; private set; } instead
got it
Here's how I do all my singleton stuff:
#region Singleton
/// <summary>
/// Singleton accessor
/// </summary>
public static FooBar Instance { get; private set; }
#endregion
Then in Awake():
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
}
else
{
Instance = this;
}
}
Cheap and easy
I'm like 1 week in and no proper schooling on it so its rough sometimes lol
but if I can get menus and save/load working I have a fully functional fun game
so I'm pushing through really hard lol
appreciate the help
gpt told me to do what you have in the awake method
doesn't work for me though since my Instance is read only which is nice
as long as my first scene has the singleton it should always exist
What are you using for menus? GameObjects in a scene or the UI Toolkit approach?
ui objects and gameobjects
getting a null error. once I hit start i go from mainmenu scene to levelselect scene
once i go to levelselect scene i get null
NullReferenceException: Object reference not set to an instance of an object
LevelSelectScreen.Start () (at Assets/Scripts/LevelSelectScreen.cs:26)
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;
public class LevelSelectScreen : MonoBehaviour
{
public GameObject buttonPrefab;
public Transform buttonContainer;
private SaveGameManager saveGameManager; // Reference to the SaveGameManager
void Start()
{
saveGameManager = SaveGameManager.Instance;
// Calculate the vertical offset between buttons
float buttonSpacing = 220f; // Adjust this value as needed
// Set the initial vertical position for the first button
float initialYPosition = 350f; // Adjust this value to set the desired initial height
// Iterate through levels 1 to 30
for (int levelNumber = 1; levelNumber <= 30; levelNumber++)
{
string sceneName = "Level " + levelNumber;
LevelData levelData = saveGameManager.LoadLevelData(sceneName);```
its still there
and you see in that code I reference it saveGameManager = SaveGameManager.Instance;
the value of Instance is probably not being set then, what did you end up with in that class?
sorry I'm not sure I understand your question.
what did you change in SaveGameManager
using UnityEngine;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine.SceneManagement;
public class SaveGameManager : MonoBehaviour
{
private static SaveGameManager instance;
public static SaveGameManager Instance => instance;
private string savePath;
private const string encryptionKeyPlayerPrefsKey = "EncryptionKey";
private string encryptionKey;
public double totalOverallTime;
public int levelsCleared;
private void Awake()
{
DontDestroyOnLoad(gameObject);```
can you show where instance is being set?
its set at the awake or start of every object that interacts with it
do I have to set it in the savegamemanager as well?
it's not being set anywhere, you're only referencing the value from elsewhere, so the value is always null
yeah, you need to set it in Awake
good point
public class SaveGameManager : MonoBehaviour
{
private static SaveGameManager instance;
public static SaveGameManager Instance => instance;
private string savePath;
private const string encryptionKeyPlayerPrefsKey = "EncryptionKey";
private string encryptionKey;
public double totalOverallTime;
public int levelsCleared;
private void Awake()
{
instance = this;
DontDestroyOnLoad(gameObject);```
logically this doesn't make sense to me though, because if I'm setting instance = this in awake, when do the fields above happen?
because I'm guessing
Instance => instance
happens before
instance = this;
before awake, but => doesn't mean assignment, it means it fetches the value from the private instance every time you write Instance
it's short for public static SaveGameManager Instance { get { return instance; } }
It's basically the same as a method returning the value to the right.
YAY leveldata! thank you thank you thank you thank you
that's really good to know thanks ๐
it loads them multiple times too
soooooo happy thank you
I spent 3 hours trying to get the buttons to scroll lol idk if I'm cut out for a scrollbar I might just make them all appear on screen instead lmao
would be cool you can see all your pb times at once as well and take a screenshot. but that convo is for a #archived-game-design
thank you all so much for the help. I really appreciate it
glad to see it's working!
Woot, so it took a a few hours, but I managed to successfully uncouple my SpellManager properly to be used by both enemies and players, and then took all the functions from my spell scriptable objects and chucked it into the Spell Manager so they're holding solely the spell's data like mpCost and cooldown.
Right now the SpellManager has to currently do some checks between spell types to figure out which Casting methods to use, which makes that class a bit longer than I'd like, and it's only gonna grow as I try to add the other spell types I have in mind. But I'll leave refactoring that to another day. Today's goal was accomplished: make sure the player and enemies don't interfere with each other's spellcasting, and that enough for me for now xD
Good to hear you got your system refactored! Do you have an approach in mind for how you might handle your spell type checks?
Honestly not at all xD I'm still new to this so now I'm afraid if I try to offload it from the SpellManager itself into somewhere else that I'll just put it in another dumb place xD
The current plan is to have 4 spell types, so Projectile, Melee, Barrier, Support. Right now the SpellManager has functions for CastPressed CastHeld and Cast Released, and then each of those functions are checking if the SpellSO being triggered inherits into a ProjectileSpell or a BarrierSpell to check what it needs to do, then it fires the shot or makes the barrier. From there the projectile or barrier handles itself.
The plan for now is to add the checks for the next two types to make sure they work how I want, then from there I'm not sure yet ๐
Im sure others might have ideas as well, though personally I would maybe have each of those types as interfaces with maybe a base ISpell, then you can make specific, generic or hybrid types (for example, a GenericProjectile : IProjectile or a specific SmokeGrenade : IProjectile or MissileSystem : IProjectile, or even a MissileShield : IProjectile, IBarrier if you wanted a shield you can throw, and then "deploys" on landing or something) - then your SpellsManager can have a list of those types or a List<ISpell>, your manager then doesnt need to know what the type is (so you wont need several checks), it can just call the interfaces Cast(), CastHold() etc, and the MissileSystem or MissileShield etc can decide how to handle the interfaces it uses
I actually did have an interface set up the first time, can't remember why I scrapped it and went the way I did, but I was thinking I should probably go something along that route, thanks! I'm gonna start looking into how to try to implement those properly. I think the problem before was I was using them weird with my scriptable objects
My spell system is composed of just a single class, I just use enums to split behaviours
targeting is generally the only reason I feel to split the class up over doing pure composition
but my workaround is always include the max targeting params and just not use them if I don't need to
Basically how mine is now. The SpellManager is the class that handles all the logic taking in the Scriptable Objects to hold any values and effects
The problem expanding the classes into their own classes is that sometimes you do want some of that functionality in those other classes. And, the more you divide these classes down, the more duplicated code you may end up having to do. So I think a heavier component approach with more comparison checking over polymorphic behaviour is the idea for these.
The downside is you may end up with some edge cases or some busted combinations but the fix to this is just don't make those spell combinations.
Anyone got a neat solution for managing the check for whether or not a coroutine has completed?
A bool isCompleted or a reference to the coroutine that is set to true/null when it completes.
Cheers, how might you go about setting that referrence value?
Hmm, I suppose the coroutine could set its own reference as its final breath... interesting
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
look at the return
coroutine = StartCoroutine(Coroutine())
Mhm, but at what point would you set that ref to null?
At the end of the coroutine
Snazzy, cheers
does anyone have any pointers or resources for understanding manipulating this grid better, its a grid script which gets filled with cells and im trying to detect when another cell beside the current cell the function is currently checking for the conditions and see if it has the desired tag on the condition, i thought this should be correct but, doo doo brain moment ig,
this is all cells are, figured i should post it
is something specifically not working? What part are you trying to change so that it works better
One last little refactor before I stop for the night xP
its not detecting the second tile whenever i script it this way,
i thought it would be as simple as adding another cell thingy and adding 1 to the x value but yeah
do you know what the difference is between ++x and x++
or try to log
cell1==cell
no idea all i know is ++ adds another increment or smthn like that, kinda forgor, i was looking into it the other night actually
or what x++ actually does
yeah no
the code isnt ++ right now though thats my bad for posting that, currently doing just x+1 in the code, that was just me seeing if thats whatt i was looking fro after i read about it a little
thank you
btw you still need to rewrite the loop a little bit for accessing
array[x] and array[x+1]
```since you will get index out of bound if the length is not multiple of two
alright noted, i understand whats happening with the For part alot more now thanks for the reference site
you mean like this? affirming I'm interpreting what you said to do right
just to be clear I didnt add cell2 cause of that, thats just to detect the other side of the cell I'm trying to do stuff on
No, just accessing two different elements in an array
Hey! Sorry for replying to your message here, I need a help with an issue that I'm currently facing after uploading the game to WebGL, will you be able to help me with the issue? ๐
I want to call a function using a broadcast from another script. If a variable is true in LaneManager script, then the function in EnemyMovement should be called. But I am facing this error: NullReferenceException: Object reference not set to an instance of an object in the line
"Lm.onEnemyRemoval.AddListener(ManageLanelessCars);"
If I check for LaneManager, it isnt null, but this line of AddListener is null somehow. Please help
(Scripts given below for reference)
https://pastecode.io/s/sy2ti73v --> EnemyMovement Script
https://pastecode.io/s/nkh097ft --> LaneManager Script
check if lm is null
then check if your custom unityevent is null
I also dont use unity events, Id just use C# events/ delegates
but thats beside the point
Your logged exception will specify a line which is the line where it was thrown on. Share this, otherwise it's guesswork for everybody
I don't see the line you're asking about in the code that you shared.
it isnt null
lm isnt null
it is there
Again, share the whole exception. If you want to be helped you're going to have to specify where the error is
Its a long ass code
Did you read my initial message?
I edited so it would be easy for u to view
how about your custom unity event? you have two things to check
Your logged exception will specify a line which is the line where it was thrown on.
Put in some effort in sharing the issue
I didnt get you sorry
Your Unity console would have logged the exception
Oh that
EnemyMovement.cs:26
The 26th line is what I shared
That is line 26 of that file
Lm.onEnemyRemoval.AddListener(ManageLanelessCars);
Already in the links i mentioned above
There is no line 26 in the code you shared
Because I have edited it to be short and concise
I cant display the whole code
Right, so for next time it would help a ton if this was specified more clearly
Only written relevant info
Anyway, the only thing that can be null according to this would be either Lm or onEnemyRemoval
Lm isnt null
thats not true
Lm is always present in the scene( as in gameobject)
onEnemyRemoval might also be null
That doesn't matter
But im not so sure about onEnemyRemoval
so i told you to log it
Literally what I said, thanks
public class EnemyRemovalEvent : UnityEvent { }
I have declared it like this
ok wait
You mentioned this is the line that throws, so it's one of the two variables
But surely this is not the case then because you logged the value, right?
why is that even a class ๐ค
So either it's an entirely different line or you didn't log it
Sorry, I misread.
OnEnemyRemoval:
UnityEngine.Debug:Log (object)
LaneManager:Start () (at Assets/Scripts/LaneManger.cs:90)
I debugged
this shows in console
Please share the whole code instead of cutting everything out
Or at least until like line 30
Okay
where?
otherwise if you log
$"hi i am {instance}"
```if the instance is null then you get "hi i am ", quite difficult to see
I will be more clear. Actually Enemy Movement script is existing on various items, various instances. So I dont want to have a reference of it in LaneManager and call that function for every reference (Because I think it sounds tedious and not performance friendly). Also there is only 1 laneManager script in the whole scene. SO i thought lets give this AddListener attempt a try
Looks like
FindObjectOfType<LaneManager>();
is not finding any objects of type LaneManager
It is
Otherwise my whole script wont be working
The spawning on lanes is dependent on that
So Lane Manager isnt null as I have debugged it
What might be the issue is in the Lm.onEnemyRemoval.AddListener(ManageLanelessCars); line
Because onEnemyRemoval is null in debug console
so you need to create an instance
In the original script I defined the class?
before others access it
or in the script in which function is called
public static LaneManager Instance => _instance;
public EnemyRemovalEvent onEnemyRemoval = new EnemyRemovalEvent();
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(gameObject);
return;
}
_instance = this;
}```
Like this?
I would be interested to see a screen shot of the LaneManager inspector
Ok, so onEnemyRemoval is not serialized. you should add the [System.Serializable] attribute to your class definition
and then? what do i serialize it with?
Unity will do that
if the class is serializable the editor will create an instance for you
if you dont want to see it in inspector then you need to do this by yourself
Okay i did that but it still doesnt solve the issue
Does it now show in the inspector?
nope
@fervent furnace this is what u were saying?
you code is mainly create a singleton
[System.Serializable]
public class ClassA{
public int a;
}
public class ClassB{
public int b;
}
public ClassA classA;//you will see a fold out group in your inspector, and the instance of ClassA is created
public ClassB classB;//you wont see anything, just a declaration
I got what i was doing wrong
onEnemyRemoval = new EnemyRemovalEvent();```
i just added this line and it fixed
Should not need that if EnemyRemovalEvent is Serializable
I have items spawning on roads. Now if the roads get destroyed or move out of scene, I want the items to move along the road in the same speed out of the scene so It doesn't look absurd to the player. Any tips how do I achieve that? I tried writing a code of mine below but it doesn't work
{
GameObject removedLaneLeft = Lm.instantiatedLanesLeft[Lm.instantiatedLanesLeft.Count - 1];
GameObject removedLaneRight = Lm.instantiatedLanesRight[Lm.instantiatedLanesRight.Count - 1];
Collider2D leftLaneCollider = removedLaneLeft.GetComponent<Collider2D>();
Collider2D rightLaneCollider = removedLaneRight.GetComponent<Collider2D>();
foreach (GameObject i in items)
{
bool isWithinBoundsLeftLane = leftLaneCollider.bounds.Contains(i.transform.position);
bool isWithinBoundsRightLane = rightLaneCollider.bounds.Contains(i.transform.position);
if (isWithinBoundsLeftLane || isWithinBoundsRightLane)
{
Debug.Log("Speed changed");
i.transform.position += new Vector3(0, ((Speed + 5f) * Time.deltaTime), 0);
}
else if (i.transform.position.x == mlp1 || i.transform.position.x == mlp2 || i.transform.position.x == mlp3 || i.transform.position.x == mlp4)
{
Debug.Log("Cars Destroyed");
Destroy(i);
items.Remove(i);
}
}```
the objects are getting spawned from above the scene, scrolling downwards to the screen (out of the scene) which visually makes player feel as if the cars are moving (2D ). The items arent paired with anything. The items get spawned on random middle road positions and move downwards. Also Theres a pickup "LaneDecrease" which can be picked up by the player, so the lanes go downward the scene (instead of just scrolling infinite) and get destroyed. Eg: 4 lanes before, then 2 lanes.
So The items which were spawned on those lanes (the lanes which are destroyed) would look as if they are on the ground and not on roads. SO I want these items to either catch through the lane's speed and look as if all items are moving with lane outwards the scene. Or if the items spawned are not visually visible and they are the items on which no lane is present, then the items get destroyed simple
Hi anyone as implemented modding to their game. I'm trying to implement modding to mine I already can import asset bundles and it everything working but the problem u cant import scripts included in the asset that u created from the asset bundle. I'm trying to do some work arround this I already tried with making a assetbundlel with .txt and then try to compile but the probllem is I cant create the asset bundle with two assets (and I already tried to compile the code in and IDE then import it to unity) to then add it to the asset but I'm having a error that I cant add it to the asset. And I'm just lost does any one worked with modding that can help me?
Hello guys!
Is there any texture format in unity where can I store multiple samples per pixel?
This is a coding channel
Yeah that is why I ask, if there is any render texture class, which can store multiple samples.
A 3d texture or a texture array.
Hey guys im super new to this and I've been stumpted on understanding player controls with cinemachine.
how exactly could this be replicated with cinemachine? More specifically, what tools/components are present in making the player follow the crosshair?
guys is it possible to integrate payment gateways in unity?
Hey thanks! ๐
What has this to do with #archived-code-general
Good morning. I'm having an issue with 'Parent Constraint' component.
I'm adding a source at runtime.
This is how I'm calculating the rotation offset (basically I'm wanting the object to keep its current rotation when grabbed by the Parent Constraint, and only rotate as parent rotates)
Vector3 CalculateRotationOffset(Transform transformA, Transform transformB)
{
// Calculate rotation offset
Quaternion rotationOffset = Quaternion.FromToRotation(transformB.forward, transformA.forward);
Vector3 eulerRotationOffset = rotationOffset.eulerAngles;
Debug.Log(eulerRotationOffset);
return eulerRotationOffset;
}
I've also tried Quaternion.LookRotation or whatever that is. The look rotation it just rotates to some crazy new angle on grab. the FromToRotation method seems to zero out its rotation on grab.
Next thing I'm going to try (since documentation isn't very clear on the offsets), is converting the rotation to local rotation.
can I change the color of individual letters in a Tmpro?
i think you can using rich text (i think thats what its called)
if you want more, and easier control, i think there are a few assets in asset store that let you do animations, and color changes and whatnot with TMP
ah
well i'll probably just have three colors max at any given point so I can probably just use three text boxes for now
Hi, thanks for the reply, yes theyโre normal buttons that call methods from onclick
The gameobject gets deactivated and the other one gets activated
if you want to parent stuff without parent rotation being applied (which I assume is what you're doing), then why not just do a rotation constraint and stick it on a non-moving object in the scene
oh you do want it to rotate with the parent constraint but undoing the constraint and reapplying the constraint to another is the problem?
try that
maybe with some rotatetowards if you need the lerp
and probably stick a parent constraint on something not moving? (well, unless you do need the parent to supply the position and not the rotation)
Does anyone got any info on something like a dependency visualizer?
Something simple, maybe node based that i can use to map systems out (purely for organization purposes)
That sounds like it SHOULD work without making the both click. Can you confirm you see it behaving as expected in the object hierarchy? (e.g. one of the button IS in fact always inactive, it just changes which one. also, better double check their state BEFORE clicking anything to confirm just one is enabled at start.)
Never mind found what i was looking for
ooh what flowchart maker is this?
lemme find it for you
i have no idea , i just found it
oh you mean within unity , nah not unless you specifically do it within a function i believe
yeah
time to have 3 different functions for three different buttons that do the same thing but have to check a different value
you could have something hold the param and have whatever function access the holder when you call the function using the button
its janky but will get around not being able to pass params in with buttons thorough the inspector
well yeah ofc you can just assign the value
but if it changes at runtime nothing you can do
button with params doesnt make any sense. It's like how do you pass something just by clicking on it? You need some variable to store some previous value somewhere and read that inside of the button.
I need some fresh view on a problem. I am making a board game and right now I move a player figurine just by teleporting it to the field dropped on the dice. How can I make a animation for movement (figurine steps on every next field before reaching its destination )and to make a method that runs logic to wait before animation is finished? Or how can I make it in the other way?
Do you actually need to animate the figure or do you just want visual movement from A to B ?
I need a "animation" in a sense of moving figure not just straight, but in sinusoid trajectory to make it look like a person counting field by moving figurine.
Should be easy with a simple script right?
Just move it there while moving the figure up/ down
where the highest height is the halfway point between two fields
I have no idea what you mean by that but, and I'm just guessing here, you do not need animation you just need something like a Coroutine implementing a MoveToward loop
expert graphic of what i think he means
Like when moving a chess piece tile by tile
Or any boardgame
ok so what I said using a Bezier Curve
I never did anything with bezier curves
look at your graphic, you have an array of start and end points, you just need a curve algo to get the movement between each one
yeah makes sense
I believe the easiest would be to have a height over distance function.
With an AnimationCurve that would be easy to implement.
would also work, there are many ways to skin this particular cat
And this simply happens in a single frame, right?
So the 2nd Button's click event gets activated instantly after the 1st button, which enabled the 2nd, is clicked
That's quite strange, I'd suppose
Consider waiting a frame before changing the buttons
firstButton.onClick.AddListener(ChangeButton);
secondButton.onClick.AddListener(ChangeButton);
private void ChangeButton()
{
StartCoroutine(ChangeButtonCoroutine());
IEnumerator ChangeButtonCoroutine()
{
yield return null; // wait a single frame
// change buttons
}
}
This should work, but I still wonder why the click event is triggered instantly ๐ค
Another option might be something like a custom OnPointerClick handler or OnPointerUp handler that consumes the event rather than letting it "bubble" down
How would you implement this to consume the secondButton's event?
You would use IPointerClickHandler or IPointerUpHandler on the button and use https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.AbstractEventData.Use.html on the PointerEventData
I don't think it's something you can do with Button.onClick
Got it
is it possible to make it so ui takes up the same amount of screen space and has about the same positions irregardless of the resolution?
messing around with the canvas stuff has not seemed to work
By what definition of "space" and "position"?
It's possible to do so for some definition of space and position but not all definitions at once
can I get the menu ui to look like this irregardless of the resolution?
(ignore the white squares, thats just what it looks like in not-play mode)
for example:
- you can anchor an image to be 10 px from the right edge of the screen.
But this will not always be the same percentage of the screen, or the same distance from the left side of the screen
"like this" is very vague
that's the problem
let me try and be more specific one sec
sure ill move there
Anyone encounter this issue when installing the Timeline package?
How to set font for each one option in dropdown unity?
The dropdown has a disabled "template" object that is used to construct options, you can modify that
See https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-Dropdown.html#the-template-system for more info on how to customize it
Yeah, I know, but how do you change the font for like your option. That is, if I have Option 1 in the list, it should have its own font, and if I have Option 2 in the list, it should have its own font
The ordering of options in the .options list will be identical to the ordering of the instantiated child GameObjects for each option. From there with the parent container of all options, get the specific child option object by index, retrieve its Text component and change the font
alright, thank you
so I'm in the need of some form of cone-cast, and google isn't helping a ton. if it was a simple LOS thing then I could use a trigger/collider to manage it, but I need to find the nearest point to the player within a cone which could be on a wall or the floor or something. Any ideas of what to look for or adapt or create to make that possible?
just draw rays in shape of cone
Every time i populate or change one of these prefab entries, it does a Domain Reload, which takes a while. Is it expected that it does that? I do not seem to recall that in the past.
I'm not sure I follow, I only know about lines and spheres and lines would probably not be the most efficient
how would lines not be efficent?
could use just use a trigger then on OnTriggerEnter fire a ray for precision
and you saw this already, i assume
https://forum.unity.com/threads/raycasting-a-cone-instead-of-single-ray.39426/
(humor my bad drawing lol) not all of the rays here would connect but some would definitely be closer than others. Can't easily raycast based on the trigger enter because the centre of the wall almost definitely isn't the closest point on it
yeah which works fine for individual smaller objects just not so well for larger ones
should probably explain the usecase to get a better option / suggestion
so making a grapple system and some feedback is that with the grapple going to the crosshair you need to be precise so ideally the grapple will automatically find the nearest point of contact and auto align to that instead, hence why I can't just use a cone shaped trigger because that won't necessarily be the closest point
(also I gtg for like 20m)
wouldnt a bigger shape like spherecast work fine here then ? it gives you more "width" to play with
hey guys, need some help with Joints - Im currently working on a mechanic for a 3d space simulator, where youre supposed to be able to chain additional ship elements to the back of your ship, kind of like a train - wagons type situation [Figure 1]
Ive set this up to work using Configurable Joints. Specifically, the player ship and every wagon has its own joint. The player ship's joint's connected body is the first wagon, the first wagon's is the second, and so on. It looks something like [Figure 2], where red is the player ship and green and blue are different wagons.
The wagons in the gif were connected manually, and the system works well enough.
However, when I try to instantiate a new wagon, and then connect it on runtime, I run into an issue: [Figure 3]
What happens is, as per the Configurable Joint documentation, if the connected body value is null, then the joint snaps to a point in world space. However, in my case the connected body is not null at that point [Figure 4], which is done as such:
I have a class JointComponent that handles joint manipulation, and it has a method Connect that is called from my WagonManager class whenever a new wagon is created:
public void Connect(GameObject connectedObject)
{
if (joint.connectedBody != null)
{
Debug.Log("Tried to connect to a joint that already has a connected object");
return;
}
joint.connectedBody = connectedObject.GetComponent<Rigidbody>();
Enable();
UpdateAnchors();
}
Where Enable just sets up the Joint values so it works (necessary to set them all to 0 so that the Joint doesn't go crazy if it doesn't have a connected body):
private void Enable()
{
joint.xMotion = _dataMotionX;
joint.yMotion = _dataMotionY;
joint.zMotion = _dataMotionZ;
...
joint.xDrive = _driveX;
joint.yDrive = _driveY;
joint.zDrive = _driveZ;
joint.slerpDrive = _driveSlerp;
}
And Update Anchors is a method that is only supposed to be run in Awake, but I tried to run it here to try and force update the Joint. The method sets up the anchor positions:
private void UpdateAnchors()
{
joint.anchor = new Vector3
{
x = 0,
y = 0,
z = -GetAbsDistanceFromWagonCenter() - WagonManager.Instance.wagonSpawnDistance / 2
};
joint.autoConfigureConnectedAnchor = false;
joint.connectedAnchor = new Vector3
{
x = 0,
y = 0,
z = GetAbsDistanceFromWagonCenter() + WagonManager.Instance.wagonSpawnDistance / 2
};
}
Connect is called after the wagon has been created:
private void ConnectWagons(IWagon parentWagon, IWagon childWagon)
{
parentWagon.GetWagon().backJoint.Connect(childWagon.GetWagon().gameObject);
}
What ends up happening is that the wagon is correctly set up as the connected body, but the ship still snaps to the world position. What's throwing me off even more is that simply "refreshing" the joint, by toggling the "auto set up connected anchor" option [Figure 5], the ship and wagon snap together and work as intended. What could be the cause of this, and how could I solve this issue?
oof discord compression did a number on these gifs lol
hopefully better view of the last figure:
(1. camera centred, no offset 2. camera centred, radius offset 3. player centred, radius offset)
I think pic 2 really highlights the issue where if walls are closer together then the spherecast isn't necessarily representative of where the grapple should be going, and although pic 3 is debateably the best solution for accuracy (still has potential issues) it's not representative of the crosshair
i need help with my code
the ideal would be something like this
I'm having some trouble configuring a nav mesh agent: my agent has very high speed and low acceleration (it's a large boulder), which gives me the desired effect of building a lot of momentum.
The problem: when my agent hits a wall, it retains the speed it had, so if it goes into a corner, it sitz there still as it slowly decelerates all the speed it's holding onto (despite visually being still). Is there a way to make it lose/transfer it's speed as though it were a rigidbody going into the wall?
Does anyone have any tips?
does it have a high rigidbody mass?
https://github.com/walterellisfun/ConeCast/blob/master/ConeCastExtension.cs also I did see this which feels like it could be better but I'm not sure what the best way is to get the closest hit out of it and whether it would be efficient to run that even past the wall
Yes- will that cause weird velocity issues with NavMeshAgents?
well it's physics, so my assumption would be that a lower mass would let it decrease the momentum faster but idk. Could also try experimenting with drag
For the purposes of getting around Domain Reload (I mean, i want to turn it off) is a Singleton considered a Static method?
Oh I meant like, collisions dont seem to affect the agent's velocity at all
Something like this
When ideally it'd lose most of its velocity when it hits the wall
for step 3 do you mean when it collided with the wall or?
Unity is ignoring the fact i have Domain Reload off, kind of. 2022.3.26 when i chage a SerializedField it reloads domain, even though i have that disabled for playmode. I have 4 things to populate here. this is going to end up taking too much time in the end. I have already removed things like Visual Scripting and some other packages. this still take too long.
Yeah so lets say it's traveling 3 units per second, it'll hit the wall, slowly slide over to the side over a couple seconds, then once it's free of the wall continue off as if it hadn't hit anything
I'm not sure your physics are physicsing
that's not how momentum works irl so idk why you expect it to do that in unity
Yes I agree, that's the issue I'm having- the NavMeshAgent is holding onto its velocity for some reason
It'll push them regardless of mass- for instance it (even at 1 mass) clipped me through a wall
I mean if it hits the player what should happen, should the player die or?
Oh for now I just have some debug methods printing if it hits a player, it'll run a Kill method on the player eventually
The movement has nothing to do with rigidbody. The navmesh agent controls where it goes. It just might happen that your rigidbody is also messing with things.
Do I need to manually set velocity changes on agents?
in which case you could always do something like onCollision(Collider collider) { rb.velocity = 0;}
would not be surprised if the navmesh impacts more here though
If you are using navmesh agent movement, your rigidbody should be kinematic
and if it is then my velocity thing won't do anything probably
The velocity was already either doing nothing, or it was fighting the navmesh movement.
figures
I should clarify velocity refers to the velocity field of the NavMeshAgent
in which case my code would work, but change the velocity of the agent not the rigidbody
Are there any events associated with NavMeshAgents? I don't see any in the docs but I figure it wouldn't hurt to ask
Your issue is probably more related to why it's even trying to path into the wall. Maybe you need to bake the navmesh again
For the people here that use Tiled to create their maps (Platformer/Topdown/etc), how do you get an individual tile's custom property?
I currently have some janky setup where it's only able to get the custom property of the Layer
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 dont normally use unity. i use godot. but theres this game called YARG which is open source and im trying to export it to see if i can get it to work on console. What visual studio components do i need to export it as UWP? i downloaded the right workloads but now its just really vauge and is telling me it dont have the right components.
hello, can anyone help me figure out how to add the Test Framework experimental version in package manager? I haev "enable experimental" checkbox there, but I don't see t he latest when searching for Test Framework. Does anyone know how to add any experimental package to unity? I think maybe I can do it using the "git URL", but when I tried it didn't work
Does async/await have an equivalent of yield WaitForNextFrame? (Im being forced to use async for Meta Quest SDK)
I just want to wait for a bool condition to become true before finishing the async Task
how could i add Aim Constraint Sources with scripts? In the editor I can just drag in any object I want, but in scripts (using either SetSource or AddSource) it says it has to be a animation.constraintsource or something
im not trying to do any complicated procedural animation, just trying to rotate one object to face another- and change that object with scripts
Yes. Task.Yield() iirc.
show codeyou wrote
im not having any code problems (i mean i am but you know what i mean) i just dont know what to put in general
this is what i imagine it would be
target is a game object
this
https://docs.unity3d.com/2023.1/Documentation/ScriptReference/Awaitable.NextFrameAsync.html
if ur using unity 2023 yes
Just found that. Iโm not using 2023 unfortunately
this is not underlined you have to configure your !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 have the thing that underlines errors
used to but it stopped
idk why
yes well you should get it working again
I think Task.Yield() will be the way to go for now, thanks
no nuisance to me so i will eventually
im just tryna get this fixed first
getting you to configure it is part of the requirement before getting help
getting the proper types, parameters suggestions when you're writing is part of avoiding these issues
enabled what? working what?
show
show that is underlining the current error
dont see why but
also have you looked here https://docs.unity3d.com/ScriptReference/Animations.AimConstraint.AddSource.html
super empty
doesnt have anything that i can read in english if you know what i mean
its literally
like i know it adds a source
but how does it work unity doc... tell me....
same thing
what
exactly
exactly what bro ๐ญ
so how exactly do i set a constraint source for a different object
mannn i dont even got an emoji for this one
coding is not for you if this frustrates you quickly
Pass in the transform for that object
As the sourceTransform
have some milk child
fixing a problem involves a series of correct steps, you want to skip to "the fix"
it still just comes out as 'set as Animations.ConstraintSource'
because thats the object type it expects..
Well you have to pass it in as a struct
Create the ConstraintSource struct with those parameters navarone shared. Then pass in the struct
nvm figured it out
for anyone looking back (or the mods looking at the edit logs) this is why i dont like coming to the unity discord
people dodge actually helping and instead just send unity links with no explanation.... its a cruel world for people that arent already multi-million dollar game devs with the entire knowledge of the unity universe...
Hello everyone, im wondering if theres a way to create a drawn path in unity like blender has.
ideally i can get most to all points of this line and save it to create a path
(im hoping to avoid whats seen in the image with the green background, having to create a bunch of empty objects or elements to create this path)
(its 2d, not 3d)
the closest without custom tool would probably unity's spline tool
you can't draw points but every click it places a point and smooths out between points
uuh fancy, thank you
Hi, have a nice day guys.
I'd like to ask is there any way to serialize an enum property? I used [field:SerializeField] but it did not work.
that should work just fine provided it is an auto property and is not readonly
Enums are nothing special. Show your code
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
public class ButtonOnHoverPreviewImage : MonoBehaviour
{
private RawImage PreviewImagea;
private RawImage PreviewImageb;
private RawImage PreviewImagec;
private Texture2D previewImagea;
private Texture2D previewImageb;
private Texture2D previewImagec;
// Find the GameObjects with the specified names
GameObject objectA;
GameObject objectB;
GameObject objectC;
private void Awake()
{
}
// Start is called before the first frame update
private void Start()
{
// Load the .png file from the Resources folder
string buttonText = GetComponentInChildren<LevelButton>()?.GetLevelNumber().ToString();
Texture2D previewImagea = Resources.Load<Texture2D>("Materials/LevelImages/" + buttonText + "a");
Texture2D previewImageb = Resources.Load<Texture2D>("Materials/LevelImages/" + buttonText + "b");
Texture2D previewImagec = Resources.Load<Texture2D>("Materials/LevelImages/" + buttonText + "c");
Debug.Log("buttontext:" + buttonText);
// Find the GameObjects with the specified names
objectA = GameObject.Find("LevelSelectImagePreviewImagea");
objectB = GameObject.Find("LevelSelectImagePreviewImageb");
objectC = GameObject.Find("LevelSelectImagePreviewImagec");
objectA.SetActive(false);
objectB.SetActive(false);
objectC.SetActive(false);
I'm debugging on hover. The only variable that actually sets to anything is the buttonText part
I have gameobjects in the scene with those exact names. and they are set to active.
and I have images to test with at those locations
also you should ditch find and just drag the reference to the desired objects in the inspector instead. you will be guaranteed to get the object you want that way and you won't have several searches through the entire hierarchy
I would but these are instantiated objects
I read through the link and I haven't seen anything I'm doing wrong. I'm still looking though
even more reason to not use GameObject.Find. pass the references when the objects are spawned
I'm really uncertain on how to do that
sorry I think I've just been trying for 3 days and it's not clicking
I don't see how these can help me even though that's literally the point of the page
these provide much better ways to refer to another object than just using GameObject.Find which not only relies on the gameobject's name (which is brittle), but is also slow as fuck because it searches the entire scene until it finds an object with exactly that name
you also won't run into issues where one object spawns something and another is searching for that spawned object before it has even been spawned
yeah I get why it's bad, I just don't know how to access these with code, even looking at that page and the examples. I think it's just not connecting for me.
have whatever is spawning them pass them to the object that needs the references to them
oh
lmao that sounds simple brb ty
although
the .png seems super easy
and I have no clue why
I went step by step my code is same as the reference you linked
because you didn't actually read the page i linked about how Resources.Load works
don't just read the code
i read it 3x ๐ฆ
I didn't
off the top of my head it said dont include extensions, its not case sensitive, the root is the resource folder
so then what folder must the objects be in for Resources.Load to be able to find them
Assets\Materials\LevelImages
and has it clicked yet?
I mean I see what you're saying I assumed assets was the resources folder
because thats what the examples used
and I don't have a resources folder
so make one?
will do thanks
my last step is passing the 3 objects to the instantiator and having it pass them down to it's creations
which is the other part that was confusing me I'm sorry :/
I've been at it for a few days it's all looking the same to me now
I got it to work but I don't want to settle for the roudabout find way so I'm gonna keep trying the direct passdown way
if you need help with your implementation, you'll need to show what you've tried
// Instantiate button for the level
GameObject buttonGO = Instantiate(buttonPrefab, buttonContainer);
LevelButton levelButton = buttonGO.GetComponent<LevelButton>();
levelButton.SetLevelNumber(levelNumber);
private int levelNumber;
public void SetLevelNumber(int number)
{
levelNumber = number;
}
public int GetLevelNumber()
{
return levelNumber;
}```
I did this earlier to pass an int. I think I'm going to piggyback off it somehow and do it again.
just so you know if you change your buttonPrefab variable to be a LevelButton type instead of GameObject then Instantiate will return the reference to the LevelButton on the instantiated object instead of the GameObject so you wouldn't need the GetComponent call there
I'm sure that will make sense to me when I wake up tomorrow
I'll be rereading all of this
trying hard to learn
100% a better way to do this but it should work
public void SetImagePreview(GameObject previewA, GameObject previewB, GameObject previewC)
{
objectA = previewA;
objectB = previewB;
objectC = previewC;
}
public GameObject GetImagePreviewA()
{
return objectA;
}
public GameObject GetImagePreviewB()
{
return objectB;
}
public GameObject GetImagePreviewC()
{
return objectC;
}```
You can replace them with properties with public getter but private setter.
also consider using an array. any time you have multiple variables with the same name except for a single letter or number differentiating them, it's time to use a collection
I was doing that for my buttons since i have 30 of them for 30 levels
I'm trying to learn but lack a formal education so shortcuts or just bad practices pervade sometimes
I thank you all for the help I really appreciate it!
Hi Hello, nice to meet everyone ๐๐, i have a question, context: im creating a Web game so i have to export to WebGL format (HTML5), but how can i protect the source code, cant anyone just inspect developer tools on the site and take it? PS: ( the code is preferably hidden )
Thank you if you could be able to help ๐
You cannot, even if it's not WebGL.
Oh i seeโฆ
Well, the source code is not exposed. It's compiled into machine code that is ultimately what's executed. People can decompile it and get a somewhat working, but unreadable version of your source code.
If you're worried about people decompiling your game, well, too bad. Even AAA level studios can't do anything about it.
Machine code? When i export it, i think its in html5 though, is it not?
It's probably WASM.
You can not make a game in just html 5
But yeah, don't bother with that. Instead focus on making your game fun for the players first, then deal with people stealing your code/cheating later.
encryption first, game never
What does you mean mao?
it's a joke
make the game then deal with your encryption methods because what is there to steal otherwise haha
Oh i seee loll
Well i guess i learnt today that you can literally take any game on the internet
Thank you very much ๐
I've got sort of a strange request. Imagine I wanted to make a scroll or some type of object that "opens up".
I want to create "control points" which are gameobjects that handle the scaling of the sprite mask for the contents of the scroll.
Aka the mask stretches so its edges are always at the control point position.
Is there a way to have this behaviour in the editor?
Or is it only something I can really do in play mode.
Quick question regarding architecture: I find myself using static Actions more and more to avoid using FindObjectsOfType<T> on dynamically created objects. Currently I am working on a Toady Road clone where safe zones appear each x level segments. Ofc I could tell them to look for the game manager (via singleton i.e.) and connect them this way. Telling the game manager to listen to a static event s_OnNewRespawnPoint<Vector3> is much more convenient though.
What do you think? My intuition tells me that in small projects this is no problem but will become a problem if the project is bigger. Is calling actions like s_OnNewRespawnPoint<Safepoint> with the script broadcasting a reference to itself a possibility too or is this considered bad architecture?