#archived-code-general
1 messages · Page 130 of 1
I think the function is occurring once for every object - not sure why. If so, the individual would be able to avoid a loop and just keep an index and reset on triggering of the rename command. @leaden ice
Hence the "removing numerical characters"
Yeah that's just a poor approach if that's the case
I didn't write the apporach, it's literally how unity works
I don't have a say in that
as I said, it's an editor script which occurs when you select an option from the right click menu :/
Anyway removing numbers from end of string: https://stackoverflow.com/questions/27289054/removing-numbers-at-the-end-of-a-string-c-sharp
Combine that with using the sibling index or a loop or whatever
that doesn't really sound like unity issue to me honestly
I am not the one who said it's a poor approach, I just said I don't have a say in the way it works
Rename using Blue's suggestion once and escape/return on every other iteration.
exactly what I've been trying to do this whole time, either detect that it's a second+ iteration or run the function only once no matter how many objects are selected
It really is just a simple copy of original string name plus for loop concatenating index.
Or:
string plain = RemoveNumbers(obj.name);
obj.name = $"{plain} {obj.transform.blingIndex}";```
I would really love to do that but how am I supposed to store the original name :/
Whatever the case is, I'm not writing code. The others have got this.
You parse it from the name e.g. #archived-code-general message
You'll probably want it to remove trailing whitespace too
So, get the base name, remove all the numbers and then add the index to the end of it.
It makes sense but what if there are numbers in the base name?
and that's exactly what I am saying, I don't want them removed
Apple 132 becomes Apple becomes Apple1
if I have a Plant Type 12 I don't want it to become Plant Type 1 but Plant Type 12 1
the only way to do that is to keep track of those "base name" somewhere, which sounds like a lot of work for not much advantage
Then it's not a possible problem to solve unless you encode the "base name" in a custom component or something
There's simply not enough information
so then the only approach would be a dialog
If I can suggest something
thanks
That would work too yes
Having the user input a name
rename you base object like so : Plant_Type_12
I can't predict what a user will name it
then you can parse this to inlcude the numbers as well, and use the spaces to rename stuff
Then you can't do it.
unless you control that same behavior
ok, may I ask if there are docs available because I couldn't find any
if you have control over the what the user will name it, then you can do it, otherwise, not
I put "unity input field" in Google and got this:
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-InputField.html
Have not used it myself, but seems to be what you are looking for?
Heya, I'm trying to set up my game for Steam Deck. I currently have a script with this line in the Start() function:
Time.fixedDeltaTime = Screen.currentResolution.refreshRate;
Which is supposed to set the Phyics TimeStep to match the current monitor's refresh rate. This works great on PC, but not on my Steam Deck. It seems to set the value to 60 despite my Deck being set to 40Hz, and this results in some nasty juddering with physics movement. Does anyone know why that is happening, or how I can get a more accurate reading, or what else I can do to fix this?
It's a UI input field, I need the one that works in the editor so I am trying to make one my self now, thanks either way
Oh I see, sorry for the misunderstanding!
while I don't know. I feel there should be a channel for platforms like this. There's 4 and none of them cover steamdeck or many other in fact. Maybe a general platform channel for help. Code stuff if probably not the place for this imo
I agree a steam deck channel would be nice. But I am specifically trying to figure out what code to write to achieve a specific outcome, so I figured here would be best
are you sure this code is right? Maybe it's silently throwing out your attempt to change it, and your default fixed rate is already 60 updates/s
That's quite strange @wide path
I would only assume it would be a limitation / configuration thing on the deck itself
Because if the code works, it should work on the deck as well.
The software wouldn't vary THAT much... right?
Yeah my pc has a 144hz monitor, and I can see the timestep switch from default 0.02 to 0.006944444 in project settings when I press play
Well you can set the refresh rate on the Deck, so I'm thinking maybe it is defaulting to the maximum value or something
Or maybe it's a compatibility thing since Deck is linux
Screen.currentResolution.refreshRate is an int though, so it looks a lot like you're trying to set it to 40 seconds per fixed update
Oh ya lol, I fucked up the code since my last test haha
The line I tested before was
Time.fixedDeltaTime = 1 / Screen.currentResolution.refreshRate;
Er, yeah
why does the physics timestep need to match the screen refresh rate?
a bit weird tbh 
perhaps you meant to use https://docs.unity3d.com/ScriptReference/Application-targetFrameRate.html instead?
So physics movement will look perfectly smooth. Using interpolation doesn't work in my case
Can someone let me borrow their Fade In/Out scene changer?
i am in need of something and i am pulling up 054303053405630530530560305345052340123042304230452045E+30 tutorials on yt
and so far 7 of them are trash im told
Hmm I don't think so, I have it set to use vsync and the game is rendering the correct amount of frames per second, it's just not calculating physics at the same rate
And so the mismatch is causing a judder
there’s probably something else that’s the issue then. The physics timestep should be the same across both platforms if you want to have similar behavior between the two platforms
anyone?
Who told you that 7 of them were trash?
Whoever did, probably has a script 🤔
This series will teach you how to handle level loading in UNITY. Through out the series we will be focusing on:
- Loading levels
- Fading to black and fading to clear when a level is loading
- Playing a cutscene with audio when a level has been loaded.
Click the link below to download the project files, and try out the project in the web pl...
Yeah the difference in behavior is negligible and I'm ok with that, as long as the physics look smooth no matter what refresh rate monitor the game is being played on
this is not valid in 2023
Yes this is an ancient tutorial when they still used Application.LoadLevel(). That’s been deprecated
Isn't the idea to just have a black rectangle to show in front of your camera while you do stuff in the background, and whenever ready, just switch it or fade it with transparency. That should be pretty easy to adapt from these other tutorial, no?
so what tutorial you recommend?
or can i steal someones via asset store
since thats all most people do now lol
You can still get sued for stealing code...
ai does a good job 🙂
That doesn't make you immune at all
Hi, I made this script for mass renaming things and there are 2 issues(one of which I kinda solved):
First one being that it opens as many dialogs as there are selected objects(fixed with a bool that checks if it's currently open but seems like a messy workaround)
Second being that when I change the value of the input it doesn't really change.
It shows the new name as long as the input field is selected but as soon as I de-select it/press the Rename button it turns back into it's original text and my items are renamed to that instead of the new input name.
Any thoughts as to why this is happening?
https://gdl.space/rokimiyeke.cs
https://youtu.be/Oadq-IrOazg Skimmed it, the code should work and the video should be easy to follow along
thx
also, the first workaround has a huge flaw because I wasn't able to get the OnWindowClose event or sm that would invoke an event on window close in order to set the bool to false then so technically, you can have multiple windows opened at the same time
fair
Is there a way to get voicedata in facepunch.steamworks
because from what I've seen there is literally no way to do this even though there are ways to read voicedata in it
Ok, I solved all the issues with this new code but there is only one left, if I close the window using the X button in the top right corner I can't open the other one because the bool IsActive stays true.
How can I detect the window closing because there is no available event?
https://gdl.space/onumerejak.cs
I tried overriding the Close() void in case that had something to do with it but it doesn't seem like it's a virtual void so I can't override it.
Bulk rename @cursive moth
using UnityEngine;
using UnityEditor;
using System;
public class Sample : MonoBehaviour
{
[MenuItem("GameObject/Rename")]
private static void Rename()
{
Debug.Log("Renaming...");
var arr = Selection.gameObjects;
if (arr.Length < 1)
return;
Array.Sort(arr, (a, b) => String.Compare(a.name, b.name));
string str = arr[0].name;
for (int i = 0; i < arr.Length; ++i)
arr[i].name = $"{str} {i + 1}";
}
}```
that's quite interesting, why doesn't it run multiple times for you tho?
Uncertain but the normal behavior is that of a single instance.
The data is unsorted though, thus the need to sort.
I see, I made the new approach(which I consider better because it's easier to use) but I can't figure out how to detect the window close.
It works fine till you use the x button that comes with the EditorWindow
is this for renaming objects with possibly different names to all the same name with numbers? this looks like a weird implementation
since its relying on sorting the strings
Haha, no it doesn't handle unique names. Would have to pray the user knew what they were getting themselves into.
Here's the window I have and I provided the code above, it works fine if you use the Cancel button but not if you use the X provided by the window because I can't set the bool to false since the event doesn't exist :/
I would probably do this differently, regex to get the name excluding an ending number then run the for loop from there
yours would kinda break when you start with Game Object 1, GO 2, GO 3, .... GO N because it would take the first one from the sort and do like GO 1 1, GO 1 2...
GameObject N, GameObject (N) and GameObject (Clone) are pretty common so you may want to consider parsing for those as well.
the approach I just provided doesn't rely on any previous names :/
sorting strings is weird because of the case of a string being shorter than another. Also it may not be obvious but the numbers in the string dont get sorted as numbers
so you end up with weird orderings sometimes
i was just talking about what dalphat wrote
your issue might be better solved in #↕️┃editor-extensions
Well, ideally you'd get the lesser in value including number of characters and value of character.
ik, all I am saying is that no string parsing/sorting is required in the first place
These are all editor stuff and should not really be discussed in this channel.
ok, I'll ask in #↕️┃editor-extensions
Ya know what's weird about this, is that the Vsync setting is capping the framerate at the correct value, but getting the refresh rate returns the wrong value. Anyone know if there is a way to just get the value that Vsync is trying to sync to?
is there a way to detect a collision between VoicelineTrig1 and something with the tag of Player, even if the script isnt attached to the parent object of VoicelineTrig1?
here is what i have so far.
//...
private BoxCollider2D VoicelineTrig1;
// Start is called before the first frame update
void Start()
{
VoicelineTrig1 = GameObject.Find("VoicelineDetection1").GetComponent<BoxCollider2D>();
//...
Watch this video in context on Unity's learning pages here -
http://unity3d.com/learn/tutorials/modules/beginner/physics/colliders
What Colliders do, and how to setup different collision geometry with primitive, compound and mesh colliders.
Help us caption & translate this video!
got a question. have a movement script and suddenly it wont let me jump and idk what i did wrong lmao https://hatebin.com/hemzebobsw thats the code. i feel stupid rn ngl
im pretty new, but nothing seems to be wrong with your code, check if your isJumping or isGrounded variables are messed up
Debug.Log("isJumping: " + isJumping);
Debug.Log("isGrounded: " + isGrounded);
why call isGrounded twice?
is you comment these both, does the issue remain?
I have a feeling this is coming from this so I'd debug by removing this part of the code first, test again and try to pinpoint where the issue is coming from.
ok so i removed the one in the fixed update and it still happens and if i remove the one in the void update it does not work\
thats the fixed update one removed
I mean. comment both of them, and just assign "false" by default to your variable. That way it should go straight to the part you want to jump test
wait. I'm looking at it more. IsGrounded is just to know if you touch the ground or does it mean you "CAN'T" jump?
cause you have unreachable code here.
ok so
isGrounded i belive is to see if im on the ground and if i am on the ground i wanna jump. i also made it so when i jump the longer i hold space the higher i go to a max limit i can set
wait so how would i fix this?
is taht coming from a tutorial or something?
no someone was teaching me and i got to isGrounded point and i decied to try to make it so when i hold space i jump higher lol
after I did this jumping wouldnt work and i couldt figure how to fix it
ok take your time 
ok uno sec
wait so
isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
that one?
no. that's alrgith
I meant the condition
you already have a bunch of conditional "movement" stuff in the else part. that's proabably all you want. I can't write the code for you, but I'd start there for sure
You're already executing them in conditional statement based on the "State" of your actor
uh ok thank you ❤️
just expand a litle more and ensure they don't overlap
first thing I would do is list all "State" you want to have. I mean
move
move + jump
jump + jump
etc
its fixed but ill have to sort out the fact that it just flys when i hold space infinitly
and then see what "State" you'll need in condition to do all of that
yeah, that's what I meant by "overlap"
i wish there were vc's tbh lmao it'd be so much easier to explain stuff to peeps
ah i see
list your states. then use conditional to check if the current "State" is alrgith for you to hit the space bar or not
i got it so i made a float earlier
if (Input.GetKey(KeyCode.Space) && isJumping && !IsGrounded && !DoubleJumping)
i adusted it so it works
now i just need to make it fall faster over time and im set
lol
thank you for your help nmy guy
no problem. hope you can figure out the rest. If not, just come back here
ok thx
@honest edge do you mind if i add you so i dont gotta msg in this chat, i may or may not need some help again lmaoo
you can dm me directly. but I don't take friend request. except for my close friends
ah kk got it
Can i ask why this code need a vector3 variable to store the mouse position ? For my understanding the mouse only move in 2 dimension only so why do we need the z axis ?
you can store it in a Vector2 if you want
it will just 0 out the z
even if i'm working with 3d game right ?
yes screen space is 2D
or i have to use vector3 if my game is in 3d
you may have to adjust the Z for prospective cam iirc
depends what ur doing
Vector2 is just a struct that holds 2 floats. It doesn’t have anything to do with a 2d or 3d game. It’s just used more frequently for 2d games
same thing goes for Vector3
do you have any video example for this case ?
hey sorry. I've been trying to understand marching cubes algorithm for a bit and if anyone could explain it simpler or send me any material that would be much appreciated. I already watched sebastian lague's video and im still kinda confused about it. If anyone wants to talk about it or is confused as well we could talk about it just to try to understand it
someone please explain why setting the variable here works for mouse sensitivity, and move speed, but not for interactdistance [It is not set nor changed anywhere else]
[the x rotation is changed because I moved my mouse in game]
If it's not being set or changed anywhere else it's probably not being used correctly
I'm trying to debug strange behavior with my code relating to the Character Controller. Specifically:
- Sometimes I am able to jump multiple times midair
- Sometimes I cannot jump at all
- Sometimes I move much slower than normal
Attached is my very simple player script. I assume this is the source of the problem, but I'm not sure how or where.
https://hatebin.com/mdukiqfeqq
Additionally, here are the settings for my character controller
Can someone please make the script for 4 heroes to battle any number of monsters?
That's less of a script and more of a game concept
I want a script, please.
How much C#/Unity do you know?
If you're referring to my message, I have a weirdly formal writing style that comes from various places, specifically emails. I also think this is funny to do
If you're referring to the code, no
!mute 234441532671787009 1w you have been warned for: "Stop asking for free work. If you're not going to show your attempts, you won't be allowed to post. " and demanding scripts many times. This is your final warning, accompanied with a week-long mute. Next time you will be banned.
joeynigro#0 was muted.
I know more of Java than C#, and my current C# skill is basic. Most of my background is in Rust
What's the usual way to initialize variables, then?
Oh, through the inspector. I'll use that method then
I just remade the variable right below it exactly the same and the issue was not present (so im just calling that specific line as cursed)
^
literally 0 idea why it was being set to 100 lmao restarted editor n everything twice
I haven't used Unity in two years. Most of this has been trial and error and what makes visual sense to me
I don't know what the preferred Unity way is for doing things and I don't know where I would even find such a thing
you should add debugs to see why you are able to jump many times, im unsure about that one specifically but ive heard the character controller isGrounded value is kinda weird.
For not jumping at all, this may just be the same issue, but one thing i notice is
if (_controller.isGrounded && _movementVector.y < 0)
{
_movementVector.y = 0;
}
will immediately stop your jump if you are grounded and have any downwards force
really most of this you should add debug statements or make your _movementVector public/serialize field so you can just see its values in the inspector rather than printing it every frame
I don't know how to use samples, and when I first searched this issue online, the first thing I read said that the sample was outdated and broken
Again, I haven't done anything in Unity for two years
If there's a proper way of doing things, I'm all ears
or https://catlikecoding.com/unity/tutorials/movement/ is a decent intro if you want to start making a custom one @sour matrix
can someone let me know why i keep getting this error when i try to build
Looks like PlasticSCM. If you're not using it, remove it from your package.
i did still gives me this error
This isn't really a code question, try #💻┃unity-talk
lol alright
hey guys, is there a way to make the line renderer to automatically targets the enemy object when i shoot?
thinking of like no matter where the player is facing but the line still shoots at the object/nearest target
heres the code for it
you need a reference then to the nearest object, however you calculate that. Then just set the position of index 1 to that nearest object transform position
you are setting transform .forward as the ray's position...
Is there a way to turn byte arrays into audio clips?
You can basically write to any file format, what are you trying to do though?
yeah i just set it to forward for now cuz i have no idea how to reference the targeted object lol
So I'm trying to get proximity voicechat to work in my game and one way you can get voice data is by byte. I'm currently just trying to find out how to convert the byte arrays to audio clips so you can ofc hear it
Another way you can get audio data is MemoryStreams but I first want to start off more simple with bytes before going to that
for naive approach, just find a array or list to store all the GOs
for complicated approach, i have no idea
wait me. Also if me what are go's
Edit: Nvm
@lean sail Do you have any idea how to do this
i havent worked with voice chats yet, but also im pretty sure theres lots of built in tools specifically so you dont have to do this
and tutorials
ok
Hello, where do I find APIs provided by Unity's Wire package?
Does anyone know if it has a API to check network connection or connection to Unity Gaming Services itself?
@rustic nymph https://www.youtube.com/watch?v=xzFsbQEqFdg
^ no matter where player is facing, picking closest target to reticle (or whatever point on screen)
ohhh thank you so muchh
this gonna help a lot
Anyone want to help me make a game for free?
no
I'm pretty sure you've been told this before
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
I don't see how that question is relevant to the rules of this server
is there a 3D Rigidbody version of OverlapCollider?
Do you have family or friends money is not all about life
?
You don't have to be rich
Physics.OverlapSomething?
Oh yeah
Like mater once said: "Money ain't gonna make you feel better"
2D physics api seem to be way different
but this is a static method of physics class not collider2d
Doubt, almost no one wants to waste their time helping others do such a hard task for free on the internet
Yeah im just converting a script that relies on 2D physics a lot to 3D physics
Money isn't all about richness it's about the amount you have
That's all that matters
What the hell is this guy saying?
@viral yacht you posted about collaboration, I showed you that that is not allowed here and where to post. There is also no off-topic allowed on this server which all your subsequent posts have been. Further more this is a code channel so why did you even post here in the first place?
Vector3 center = new Vector3(Screen.width / 2, Screen.height / 2, depth);
is this a reliable way to get the center of the screen? It looks right of course but im wondering if there are better ways, or is this the best way
Bruh
Dude chill out
Oh god he's still trying
yeah pixels but you can covert it also
Yeah, what're you using it for?
Just heavility editing someone's script to make it 3d compatible, I can't even give a good answer to that since im not done yet lol
Ah
not quite sure about your depth variable a screen only has 2 dimensions so should be a Vector2
I forgot to remove that from the snippet srry, ignore it there
and yeah its incorrect
but the general idea of dividing width and height by 2
yes or *0.5f
alr
width and height are ints, / 2 will also give an int so Vector2Int should be the result
Yeah thats good, thanks
if you want to be really optimal
Vector2Int center = new Vector2Int(Screen.width >> 1, Screen.height >> 1);
the compiler should compile any /2^n to >>n (except negative integer) so i think run-time is still the same
maybe, but if not there is unnecessary overflow/underflow conditions tested
its the asm programmer in me, I always prefer explicit bitshifts when possible
farts with upsets
enough with the bs
<@&502884371011731486>
!warn 770034486804480110 there is no off-topic, and job posting or collab/job requests are not allowed on this server.
robal9874#0 has been warned.
Any1 knows a good 3d grid system tutorial? On youtube are specific to 2D or the CodeMonkey ones are imposible to follow since the code he references from previous videos is heavily different between tutorials
What you want to know about 3D grids ? Does not seem to be something that needs to be tutorialize.
to snap gameobjects and display it
Snaping would work the same as 2D, but with an extra dimension.
Im trying to do a thing like Xcom for example
I do not know what you mean by displaying.
I'm not familiar with XCom, however Turn Base game are usually 2D grids.
multilevel grid is just a some separate 2d grids
similar to hierarchical search
To be honest, I am not totally sure what would be the best way to show a grid.
Like this, maybe i was bad at words
But right now im using a shader, that is not very acurate
It does seem pretty good doesnt ?
Yeah but what i said, its a shader so Its not really useful because of size and scales
thats why i wanted some "real" grid
To snap things well and not by hand
I mean, the shader is probably the best approach.
You just want to combine it with a code that manipulate the shader.
Hi. I have a bouncing ball game, and I wanna restrict the angles it bounces because I am using a sphere collider and the unity and rigidbody physics system ( Ireally doint wanna have to make my own physics). So hereis what I wanna do:
I wanna lock the bounce angles to 22.5 degree increments.
I have tried using several different codes but they all faulter at one point or another, could someone either show me some example code or just tell me the logical process to making this work?
here is some code I already used, I used 90 degrees to visually see if it works, but for some reason the ball still bounces at "off" angles, for example if I angle the wall 22.5 degrees the ball surely doesnt bounce at a 90 degree angle as expected in the code below
there's some artifacting because of the low resolution, I guess
oops, was scrolled back
You are not using the normal ?
If every corner is 90 degrees, I can see how you can manage without the normal, however in a scenario where it has other surface possible, you probably need the normal.
Reflection is base on the normal of the surface and the incident angle.
I see. When you say normal do you mean normalize or?
No, I mean the normal.
I would just do this in FixedUpdate and call it a day 😆
int segments = 16; // 22.5 degree angle
void FixedUpdate () {
Vector2 vel = rb.velocity;
float mag = vel.magnitude;
float angle = Vector2.SignedAngle(Vector2.right, vel);
angle /= (360f / segments); // 16 segments for 22.5 degrees. but insert your segment count here
angle = Mathf.Round(angle); // round to the nearest segment
angle *= (360f / segments); // scale back to 360 degrees
Vector2 result = Quaternion.Euler(0, 0, angle) * Vector2.right * mag; // make a vector at that angle with the original magnitude
rb.velocity = result;
}```
_note this has not been tested and I just wrote it in Discord_
In 3D yu have hit.normal.
the normal is the surface normal vector as in Simferoce's image above
it describes the orientation of the surface
I tried it and the ball gets stuck xD
I see, now I understand. I googled and apparently I am supposed to use raycast hit normal code? Or is there some other I am missing
stuck?
Yeah it doesnt move at all, it kinda stays in place
Yes, you should raycast to get the normal.
🤔 I did say I didn't test the code but that shouldn't happen unless you miscopied something I think
at worst it should go in the wrong direction
I mean, you are starting with (0,0,0)
I assumed some other code is giving it an initial velocity
If it has no velocity prior.
when I click space it gives velcoity to a preset value
Honestly I am super lost, I found this code online and just tweaked it, I am gonna check some youtube physics tutorials lol
Thanks guys
public class Purchaseable : MonoBehaviour
{
[SerializeField] private Dictionary<ItemData, int> cost;
[SerializeField] private DynamicInventory inventory;
private void AttemptPurchase()
{
}
I have this code which can be placed on a gameobject to make it purchasable. It should take in a cost and then compare the player's inventory state to the cost and if so attempt a purchase.
I attempted to define a cost by using a dictionary. This would allow me to support a cost of multiple items of different item types. However, dictionaries do not seem to be serializable in Unity. Is there a standard approach to something like this? I am not familiar with many data types in programming.
yes, unity does not serialize dictionary
Yes, one option would be:
[System.Serializable]
public struct Cost {
public Currency currency;
public float amount;
}
I've done that in several contexts (item price, weapon damage...)
Sometimes, you do wind up wanting a dictionary. You can build it at runtime if needed.
Cheers, I think i'll go with that
If absolutely necessary, you could do some inspector serialization using this callback interface https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
It's only annoying in situations where you want every choice to be present automatically
There's implementations for a serialized dictionary on the forums if you want to dig around, but just building it at runtime is what I do
Link pretty much exposes a dictionary to the inspector. Annoyingly you'd have to do this for every dictionary or make a generic serialized dictionary type. The alternative is to use serialized dictionaries from the asset store - pretty sure they're implemented in a similar fashion or some legacy runtime construction.
I've used the serialized dictionary thing from time to time, but it's a little bit fiddly
https://medal.tv/games/requested/clips/1eNHMUeJEcuQI4/d1337XRkawIY?invite=cr-MSxKTnYsMjYzNjQxOTcs
Hello,
I am attempting to make a restaurant game and the npcs coming in are supposed to sit down (animation) after their transform being set to a gameobject's transform
For some reason there is always an offset on the y - Axis, I am not sure why
I am also unable to move the object's Y axis in runtime
Components:
Rigidbody
2x Colliders (one with, one without trigger)
Navmesh Agent
Script
Animator in the child object
private void OnTriggerEnter(Collider other)
{
if (other.name == "WalkToPos")
{
nav.ResetPath();
animator.SetBool("isWalking", false);
nav.updateRotation = false;
Rigidbody rigidbody = GetComponent<Rigidbody>();
rigidbody.velocity = Vector3.zero;
rigidbody.constraints = RigidbodyConstraints.FreezeAll;
StartCoroutine(CustomerSit(other.transform.parent.Find("SitPos").gameObject));
}
}
IEnumerator CustomerSit(GameObject sitPos)
{
yield return new WaitForSeconds(0.4f);
transform.position = sitPos.transform.position;
print(transform.position + " " + sitPos.transform.position);
print(transform.position);
transform.localRotation = Quaternion.Euler(0, 0, 0);
transform.rotation = Quaternion.Euler(0, 0, 0);
Animation customerSitAnim = GetComponentInChildren<Animation>();
animator.SetBool("isOrdering", true);
ChooseRandomItem();
sitting = true;
}```
Watch Bug Help 18/6/23 and millions of other Requested videos on Medal, the largest Game Clip Platform.
so i am doing a third person movement and i've encountered a bug: when you spin on yourself too fast (clockwise or counterclockwise) the player just falls (its rotation changes even tho it should be frozen from the rigidbody component). to better understand the problem i temporarely deactivated the movement script, and found out that it's the rotation script that is causing this problem: https://gdl.space/uvozoxogoy.cs.
the script is attached to the main cam
You need to remove the y of the view direction.
the problem seem to increase when i decrease rotation speed and it seems to disappear when i increase it
Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
viewDir.y = 0;
orientation.forward = viewDir.normalized;
thanks, let me try, i'll be right back
nope, sadly doesn't work
I might not, be it is definitely what you want to do. It make no sense to look up.
Hello guys, I'm trying to get an object to look towards the player when it gets within a certain detection radius but only on one axis
I don't know how to do that, I tried this jumble of code but it's just broken:
{
Transform cameraTransform = moveCamera.gameObject.transform;
while (true)
{
//turn towards the player a bit
Vector3 objectLookDir = transform.up * -1;
Vector3 playerLookDir = cameraTransform.forward;
float angleBetween = Vector3.Angle(objectLookDir, playerLookDir);
Vector3 newDirection = Vector3.RotateTowards(objectLookDir, playerLookDir, rotationSpeed * Time.deltaTime, 0f);
transform.rotation = Quaternion.LookRotation(newDirection);
print(angleBetween);
yield return null;
}
}
ok i'll leave that in the code, thanks. but do you have any other ideas?
you also have to fix this code:
Vector3 dirToCombatLookAt = combatLookAt.position - new Vector3(transform.position.x, combatLookAt.position.y, transform.position.z);
orientation.forward = dirToCombatLookAt.normalized;
body.forward = dirToCombatLookAt.normalized;```
Though it's unclear what the difference between all these variables are:
[SerializeField] private Transform orientation;
[SerializeField] private Transform player;
[SerializeField] private Transform body;```
what does "only on one axis" mean exactly
Only on the blue axis
The z axis
so player is just an empty game object that holds the body and the orientation (as seen from the screenshot above). the body is the capsule and orientation is empty
you know like a creepy turn to face the player
There is nothing blue in this screenshot lol
Do you mean rotate only on the y axis?
the fact that that axis is the blue one means your object is already laying on its side/face
atm the bug is only occuring while using the basic cam
so I'd say the first thing to do here is fix your whole object setup
so that y is up
and z is forward
Yes it's kinda messed up I didn't import it properly from blender
as it should be
fix that first
Ok
or you will struggle endlessly with this stuff
Yeah I remember struggling with it in the past
Do you have any idea how to do that in blender?
I know it has something to do with these settings
Make sure the front of the object goes down the green axis in blender, the right goes down the red axis, and the top is up
Use Z forward, Y up
Check apply transform
please
Did you try the modification that @leaden ice suggested ? Fixing the other part.
Alright I will try that
#archived-code-general message he suggested to fix stuff in the combat cam
You might have an issue with the camera switching which mean that the code is executed anyway.
alright @steady moat thanks to the help that u provided in ur first message i managed to fix it. thanks a lot!
What was the issue ?
everything remains the same besides:
if (inputDir != Vector3.zero)
{
body.forward = new Vector3(Vector3.Slerp(body.forward, inputDir.normalized, Time.deltaTime * rotationSpeed).x, 0, Vector3.Slerp(body.forward, inputDir.normalized, Time.deltaTime * rotationSpeed).z);
}
i removed the y from this
like this?
if (inputDir != Vector3.zero)
{
Vector3 slerp = Vector3.Slerp(body.forward, inputDir.normalized, Time.deltaTime * rotationSpeed);
body.forward = new Vector3(slerp.x, 0, slerp.z);
}
It is definitly a better way.
thanks!
i can now continue developing. i have some more bugs to fix, but i'll ask that later
anyone knows how to make a world system like pixel worlds or growtopia?
Is this fine?
I couldn't get the red axis to go through the right
that looks fine
red axis is going to the right (the object's right)
I made a small tool to align stuff in my scene, bu I can't find how do I make the button (when the tool is docked) in two parts,
one Align button, and the other to show the tool settings, much like all the other Overlay tools.
Can someone help me figure out why my collision event functions are not being called?
Here is my player:
And here is the building I want to collide with
And this is the building script, and neither collision events get called
Even when I drag another building through it (I can drag them with the mouse) or move the player through it
Is it an issue for collision detection if I directly move the transforms?
I don't think static rigidbodies trigger collision callbacks with one another as mentioned here: https://docs.unity3d.com/2022.2/Documentation/Manual/Rigidbody2D-Static.html.
Oh, I see and what would I do if I just want to check if they are colliding but I dont want them to push eachother around
Kinematic body types only move under explicit control (i.e., you'd have to write code to make it react to a collision "naturally")
But from what I read kinematic bodies dont trigger collision events either
IIRC they do if you check the simulated box on the component itself
Full Kinematic Contact, my mistake: https://docs.unity3d.com/2022.2/Documentation/Manual/Rigidbody2D-Kinematic.html
Okay so my whole thing right now is that I want to use collisioin detection to find out if the user can place a building where the mouse is
Which I wanted to do by adding colliders and as you drag the building around and I use these collision events to check if the spot is clear
Is there a reason they’re static outside of just not moving? If that’s the case, I still think a Kinematic body type would cover it.
Does somebody to know if it's possible to get first line's position of TMP_Text even when it is empty?
It's easy to do, when there's written something, but not with empty one
Or should I consider changing TMP_Text script?
Perhaps use some whitespace placeholder?
yes, I do use it already
but it doesn't work in my case
Hey, wondering if someone can explain why I'm getting an error. Here's some snapshots of my code as well as the error message I'm getting
As far as I can tell I intantiated my objects correctly, yet it's saying there's no reference to said objects. I'm kinda confused why.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Alright, I'll just go to a C# specific discord. Thank you!
I don't think it's "C# specific issue"
The code is generating a NullReferenceException. It's not using any Unity specific libraries, it's all code I wrote myself. I'm sure a discord channel that specializes in C# specific stuff can answer it just as well as anyone here.
Thank you though.
Yeah it's more of a general execution error, but as you're using Unity you'll probably get redirected to this server once they see the Unity console
Guess I'll see. 🤷♀️
you should provide us with code and screenshots. Also we all would be happy to see Assets/Polygon.cs:27
public Polygon(List<Vector2> vertices)
{
if (vertices.Count == 0) { return; }
for (int i = 0; i < vertices.Count; i++)
{
if (i == vertices.Count - 1)
{
edges.Add(new Line(vertices[i], vertices[0]));
return;
}
Debug.Log("test");
Debug.Log(vertices[2]);
edges.Add(new Line(vertices[i], vertices[i + 1]));
Debug.Log("test2");
}
}
Welp
That didn't work
There we go
show verticles
it's not NullReferenceException
{
Debug.Log("Did I get here?");
generateCicumcircle();
}
It fails before that, error is on line 27
It calls the base class constructor
So you want me to show you the instantiation of the Triangle object?
no, VERTICLES
Line 27, what is it
There's no "l" in that. It's "vertices"
probably this
if (vertices.Count == 0) { return; }
List<Vector2> verticles = new(); // show me this !
//
//
public Polygon(List<Vector2> vertices)
{
if (vertices.Count == 0) { return; }
for (int i = 0; i < vertices.Count; i++)
{
if (i == vertices.Count - 1)
{
edges.Add(new Line(vertices[i], vertices[0]));
return;
}
Debug.Log("test");
Debug.Log(vertices[2]);
edges.Add(new Line(vertices[i], vertices[i + 1]));
Debug.Log("test2");
}
}
That line you commented doesn't exist?
I'm not sure what you're talking about
There is no "verticles" variable
edges can also be null here, can you not speculate and tell them to actually show the line 27?
can you show us the line generating the error
ok, gimme all code
edges.Add(new Line(vertices[i], vertices[i + 1])); That is the line generating the error
Edges is null
it's still vertices
what?
If it was, it would have thrown in the first if statement that checks for its count, though
Vertices takes no L
oh I'm absolutely not saying verts list is null
@gaunt blade it gonna take too long, just full code, please
This was correct.
Thank you.
Very dumb mistake on my part.
Didn't instantiate it.
whats an algorithm to generate seemless perlin noise on a sphere? i use a 2d texture:
private void Pixelreader(){
Texture2D image = new Texture2D(size, size);
gameObject.GetComponent<MeshRenderer>().material.mainTexture = image;
for (float i = 0; i < image.width; i++)
{
for (float j = 0; j < image.height; j++)
{
float Perl = Mathf.PerlinNoise(i * perlZoom,j * perlZoom);
Color color = Color.green;
if (Perl < thresh)
color = Color.blue;
//Color pixel = new Color(Perl, Perl, Perl) ;
image.SetPixel((int)i, (int)j, color);
}
}
image.Apply();
}
But it isnt seemless, as shown below:
Is there a way to revert a scriptable Object to the original values?
wdym "original values"
the values i have defined before entering playmode
when you change a SO it stays changed
no
you're changing the whole asset
it's stored on your disk not in memory
big reason SO not meant for mutable data
you typically copy the data to use then manipulate it in a separate class
Plus, in builds it does not behave the same (it's not saved between two executions)
So using it as a mutable data container is a big no-no
if you're using this as a save system, don't xD
no i didnt want to use it as a save-system because i was aware that it reverts back in builds. So i assumed the data would also revert in the editor
if you want to revert back just make it a regular class / struct
and use prefabs for preset values
I wouldn't recommend this approach at all but you could achieve this behaviour with ScriptableObjects (again, not recommended) by instantiating a clone of the ScriptableObject at runtime and using that clone throughout the game, this way the clone will update but the original ScriptableObject will not change
nah if it isnt intented to be used like then im going to stay away from it
That is not really what they are intended for though
What sort of system are you building?
I have multiple Enemies which can hold different kind of stats but are mostly the same generic stats you see in games (health, attack, speed ...).
make the stats live on the SO as read-only . if you keep it in a struct/class then copy values
would it be possible that c# is too fast? Im trying to destroy the childs of an empty game object. but sometimes it just skips one for some reason
but these values can be changed in the runtime :d
yes i know, but you can just make a copy of those stats on SO
think SO as preset
If you're going to write to scriptable objects, always make instances. Doing it this way would also allow you to 'revert' to the original values depending if you want to create a new instance or just read the original values.
it can say , this Stat holds "attack 20, defense 10 etc.."
but in the enemy class you copy those stats into the class to change at runtime
ah ok i get your approach
What I would do the that is have a seperate save system, let's say you save stats to a JSON file "Stats.JSON", then on load you can read that JSON file in at runtime and use that data to dynamically create ScriptableObjects. This way you can save/load from the JSON file. If you wanted purely a ScriptableObject approach, just have the stats but there are ways to use apurely ScriptableObject approach as well such as copying values from the enemies into the scriptable objects and keeping them up to date
How do I modify the properties of a Sprite asset from code? Looking to change things like SpriteMode and shit.
probably using preset
preset?
I have a sprite sheet with a ton of sprites. I have a json which describes what region of the sprite sheet contains what sprite.
So I want to programmatically define the many sprites in that sheet.
I recall this is how I had to do it . I made a script that makes screenshots out of scene view but it was saved as texture and not sprite so I had to make a script + preset to change ALL the images that get put into that folder automatically to sprite type
Hey so I have this piece of code which... works but the object moves and keeps jittering for some reason:
{
Transform cameraTransform = moveCamera.gameObject.transform;
while (true)
{
Vector3 objectToPlayeDir = (cameraTransform.position - transform.position).normalized;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, objectToPlayeDir, rotationSpeed * Time.deltaTime, 0.0f);
transform.rotation = Quaternion.LookRotation(newDirection);
yield return null;
}
}
For context if anybody else wants to help I'm trying to get an object to look at me but for some reason here ti moves too
what do you mean by jittering? rotation?
nice player btw 🥰
Like this
thank you, it acc a test enemy i made to test if I still knew how to blender
I see
I guess your issue is here:
Vector3 newDirection = Vector3.RotateTowards(transform.forward, objectToPlayeDir, rotationSpeed * Time.deltaTime, 0.0f);
try to increase 4th parameter
from 0f to 10f, for example
Thing is I just followed the documentation which did the same thing
What's increate?
increase*
Why would I do that and how
That parameter isn't relevant at all
change from 0f to 10f
Yes that was my thoughts as well
The maximum allowed change in vector magnitude for this rotation.
I would guess the issue has to do with another component on the object or something
The components
Although for this use case I would probably be using Quaternion.RotateTowards
Yeah the Rigidbody
wait, not, I think that's not what we need
What's up with it
If you're rotating a Rigidbody you'll want to:
- do the rotation in FixedUpdate
- use RB.MoveRotation
- enable interpolation on the body
Aha
I missed that thank you
Do I use the same technique I used here for rb.moverotation?
{
Transform cameraTransform = moveCamera.gameObject.transform;
while (true)
{
Vector3 objectToPlayeDir = (cameraTransform.position - transform.position).normalized;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, objectToPlayeDir, rotationSpeed * Time.deltaTime, 0.0f);
transform.rotation = Quaternion.LookRotation(newDirection);
yield return null;
}
}
Thing is I'm doing this in a coroutine
Hey, how do i do to make the UI element the biggest that it cans in the anchors that i set?
set its RectTransform's position's stretch to maximum
with Alt key
what if you increase rotationSpeed here..?
here?
yes, press alt and click bottom stretch
How can I acces the fill float on my material via code? The float comes out of a custom shader.
but my logo will be streche
i wan t something like this
yes, setting it's stretch to maximum gives it 100% width and 100% height of parent component
WaitForFixedUpdate then
that's what you asked for I guess ??
..how do i do to make the UI element the biggest that it cans..
Is that a function?
yield return new WaitForFixedUpdate();
ah no sorry i meant to keep the aspect ratio and make biggest that it cans in the anchors points do you understand?
no, I don't
It's a yield instruction for a coroutine
ok the circle is my sprite and the anchors points are represented by the rectangle so i wan t that
but if I got you, you need to change these parameters
these are offsets
that appear in stretch
but how can it works for every screen resolution?
No you use this #archived-code-general message
Does anyone know how to get the left and right triggers. if (Input.GetKey(KeyCode.Space)) throttle += throttleIncriment; but referencing the left or right trigger on a controller instead of the Space Key
ahh instead of yield return null
Set it up in the input manager and use GetButton
I don't get it. there gonna be the same offset on every screen resolution
But when I do that it's an axis. Does get button allow me to use it like a key?
yes that s the problem i don t wan t this, but this
thanks
GetButton interacts with axes. That's how works
That's the only thing it works with in fact
can you formulate your issues better ?
ok. What would the left triggers name be
there's a lot of conflicting info out there
You need to 9 slice the border image
No idea
Google it or experiment till you find it
thanks
what do you mean?
i wan t a sprite in my UI i wan t in the rectangle represented by the anchors points but i don t want my sprite to be streched
should it be e.g. 40% wide & 50% high of screen ?
I still don't understand :/
for example (you mean the image have a aspect ratio of 40:50)
maybe I do
I don't know if that's possible in Inspector, but that's sure possible in script
it's like
smth.width = .4f * Screen.height;
i found something, RawImage i guess it can helps
ok thks i will use that if i don t find anything
throttleup = Input.GetButton("Throttle Up");
This is coming back as an error
thks for help 👍
you currently are waiting null or exactly one frame. You want to wait for the next FixedUpdate so that the coroutine is synced with the physics time step. https://docs.unity3d.com/2017.2/Documentation/ScriptReference/WaitForFixedUpdate.html
ohhh that makes sense thank you
@gray mural oh no 🤣 i found it it was just that
what's that?
the Image component, you can set preserve Aspect to True and it will do what i wan t
It's still moving towards me :(
Yes, preserve Apect just doesn't stretch your sprite. Your sprite's resolution stays the same, when stretching
{
Transform cameraTransform = moveCamera.gameObject.transform;
while (true)
{
Vector3 objectToPlayeDir = (cameraTransform.position - transform.position).normalized;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, objectToPlayeDir, rotationSpeed * Time.deltaTime, 0.0f);
Quaternion newRotation = Quaternion.LookRotation(newDirection);
rb.MoveRotation(newRotation);
yield return new WaitForFixedUpdate();
}
}
I changed it
could anyone help me with this error? I got it while trying to build.
An asset is marked with HideFlags.DontSave but is included in the build:
Asset: 'Library/unity editor resources'
Asset name: DefaultReflectionForPrefabMode
I tried looking in library but I don't have a unity editor or defaultreflection.
and I don't think that's what you have described. You should have explained it better 🙄
your should reimport your asset
how can i make local multiplayer work
formulate your questions so that we can understand
i asked how i can make a local multiplayer. local means 2 people on 1 pc and keyboard
google it. In local multiplayer there are minimum 2 players that are controlled by e.g. WASD and Arrows
I want to check if my player is grounded, and I'm using this code:
bool is_grounded = Physics2D.CircleCast(ground_check.position, 0.5f, Vector2.down, 1f, 6);
where ground_check is an empty placed at the feet of my character. Thing is, I don't know what to do with the distance attribute, in this case, the 1f. Any help would be appreciated
why don't you just use OnCollisionEnter2D?
What error? Did you actually make an axis with that name?
because the circle cast thing is the only one I could remember xD It's been years since I've done unity stuff. How does that exactly work?
this method detects collision between collider that script is attached to and other colliders
Your method is better imo. With OnCollisionEnter2D you need to be cautious of walls (as colliding with walls would trigger the method). If your walls are floors also, it makes it even more trickier.
so you should check is collision's tag is Ground and than do stuff
no, why? you just check the ground's tag
What if the wall is ground.
AKA a platform
yeah, that depends
I got it. I was the wrong joystick buttons. I had to use the third axis
if they do not have ground walls, using OnColisionEnter should be better
Okay so, how would I fix my code? I'm currently logging my is_grounded variable, and even if I set the radius of the sphere to something big, it says i'm not grounded. What could that be due to?
Honestly, you may be better off using https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html and doing it on your "ground check" point.
Ah, okay. Let me try then
are you sure that your Ground is on correct layer?
cause I am not sure
As for why you're not "grounded", I'd need to see more information (i.e the position of your ground check)
Yeah I was wondering, if my ground layer is on layer 6, do I input 6? or 7 because it counts from 0?
int groundLayer = 6;
LayerMask groundLayerMask = 1 << groundLayer;
try using this
bool isGrounded = Physics2D.CircleCast(groundCheck.position, 0.5f, Vector2.down, 1f, groundLayerMask);
what's the reasoning behind doing a bitshift?
also make sure distance is enough
If you think the layers can change at some point you can alternatively put:
public LayerMask MyLayerMask;
And then use that in your physics.
so you should first try if that works.
yes, that's even easier.
The inspector will let you check the layers you want to check 🙂
well, I just tried a mix of both solutions, I used overlapCircle and the 1 << 6 for layer mask and it works. Altough I still would like to know why we are bitshifting?
Because layer masks are a single int
By doing 1 << 6 you're saying the 7th bit should be 1.
Ohh I see. Well thanks a lot you both :D
Does anyone know where TMP_LineInfo.lineExtents is changed?
I just need to find this in unity's code
And I don't see any methods in TMP_Text that do it (have printed them)
it's just min = Vector2(0, 0) and max = Vector2(0, 0), when nothing was typed in TMP_Text yet
reimporting my assets didn't do anything. Looking online they told me to search in project for "t:Prefab DontSave" and all the related ones, but that didn't come up with anything either.
does anyone know what could cause this type of glitch
what are we looking at and how's it related to code
looks like clear flags insnt clearing
or w./e flags on cam
yeah, hall of mirrors moment
camera settings are wrong. this is what you'd adjust in the HDRP.
thanks
Hey im struggling a bit to implement a clean solution for ObjectPooling for GameObjects which all inherit the baseClass Enemy but are different prefabs and should be pooled in different ObjectPools. Ideally i would only provide the list of all enemy types.
this will solve all your problems
don't spam
how is that spamming
offtopic is spamming in away
no its not spamming is repeatedly saying something
<@&502884371011731486>
i've never been accidentally pinged!
myb
lol
hit c too quick
i was already looking at the chat.
w/e they probably got auto kicked by Dyno
!warn 833097364704591924 There is no off topic here.
Bossmanduty916#3210 has been warned.
Oh wait, this isn't your first rodeo.
!ban save 833097364704591924 Banned for spamming. 
Bossmanduty916#3210 was banned.
You can do object pooling a few ways, if you object pool the base type, you're going to have to change the components to the more derived type (or if composite, just change the data needed) each time you pull it from the pool. Another idea is to queue a more derived prefab type, which is actually something I seen in networking because of sync issues.
Benefits of the first way, single queue and can instantiate all the objects you need early on. Benefits of the second way, less component/data injecting, and syncing if needed
everytime i try to load my project it just pulls the unity bug report
no, that's not what you should do.
Don’t crosspost. This is not a code problem
Oops
Wrong reply. You get the idea
damn phones
@visual glade
Im testing some code, and im not sure I understand whats going on, ive decided to use the ScriptableObjects InstanceID instead, my original approach was to make a public property and generate a GUID with each scriptable object once, and be able to use that in a Dictionary elsewhere:
public SomeSO : ScriptableObject
{
public string ID {get {return id;} }
string id;
void OnEnable()
{
if(string.IsNullOrEmpty(id)) {id = new GUID();}
}
}
This works fine, though whenever the project is re-opened, OnEnable will get called again on every SO (which makes sense, and is fine), but for some reason I dont understand, it will also re-assign a new ID, as if its just reset to null when Unity closes, why might that be? I tried setting the SO to dirty as well and AssetDatabase re-saving the file - the assets instance ID doesnt change between re-launches so I figured ill just use that instead, though id like to understand why this GUID approach may not have worked?
I dont really get second part. What do you mean exactly by queuing the the prefab type
apparently the problem was the way i restructured MouseSceneSpace
Ask in #💻┃unity-talk .
An example would be a prefab of base Enemy. This prefab alone may only contains defaults, but no actual identity to a specific enemy, and thus require inserting its data as you call it from the pool.
You can also make prefrabs of a full constructed enemy, such that no extra work is needed when called
Ideally, queueing the base type is what you want to do in most cases
Sorry for the confusion, I meant I did that and the other suggestion and neither worked.
right, then I don't know, sorry
np, I'll go back to the try and true method of saving a copy and then go back and slowly delete things until it works.
consider using git
git? what is that for?
git helps you to organize your project
and also makes it easy to return your project to its previous versions
Ah, yea I'll definetly need to try that out, thanks.
Hello guys, I have a problem with getting an rigidbody object to look at the player when it comes within a certain range
This is the code that I use:
{
if(other.CompareTag("Player"))
{
StartCoroutine(TurnTowardsPlayer());
print("Player is detected");
}
}
IEnumerator TurnTowardsPlayer()
{
Transform cameraTransform = moveCamera.gameObject.transform;
while (true)
{
Vector3 objectToPlayeDir = (cameraTransform.position - transform.position).normalized;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, objectToPlayeDir, rotationSpeed * Time.deltaTime, 0.0f);
Quaternion newRotation = Quaternion.LookRotation(newDirection);
rb.MoveRotation(newRotation);
yield return new WaitForFixedUpdate();
}
}
But instead it doesn't just rotate to face the player but instead moves towards it too
Video
is that the only script you have on enemy?
Yes, these are the components:
hmm never used MoveRotation. does it work without out it?
like does it not move
does anyone know how i can change my web swinging, currently to pull towards the web you pull down on the trigger but i want it so you have to pull on the web and then let go? anyone know how i can do that? in vr?
What do you mean, another function? I tried rb.rotation and it's the same thing
Wait I noticed this
no i mean if you comment it out
does it still move
It waits it rotates then moves for some reason
So I have some animations for a sprite. The state of my sprite is handled completely by scripts. I don't want some complex state machine controlling the animations. I want all transitions to be instantaneous. How do I set up the animator to achieve this behaviour?
No then it doesn't do anything
Should just be able to play the clips even without animation transitions
hmm i normally use .AddTorque but im sure there is a reason why it's moving
Does someone has been working on a game and has been using Steam Inventory using Steamwprks.NET? (please reply with ping)
How exactly?
okay
Throw on an animator and feed it the clips like normal
Ah there's "Animator.Play"
I fixed it
Apparantly I shouldn't have used this other transform it was weird
huh?
So here
I have the rbcharactercontroller
and cameraholder
I used the cameraholder instead which is weird I don't wanna get into it
oh alright, just didn't know why that method moves it too but reading the docs now it makes sense why it does
i never used it before
Yeah, if needed, just link all clips to the entry point but it may not be needed. I forget
you'll want to loop stuff on the clip itself if not in the animator such as running
just wanted to give you an update that I did indeed figure it out, I just had to make a new scene and move everything over from the old one... I don't know why but it worked.
hi. I can't seem to get the freeze Z rotation constraint to work. I have a cube with a rigidbody that I can tilt up and down and rotate left and right using AddTorque. If I rotate while x=0, it works. if I tilt first, then rotate, it changes the z-axis. I have Freeze Rotation : Z checked. How can I make the cube spin around the Y axis in world space instead of tilting on the z-axis? This is how I'm imparting the rotations:
private void ApplyYaw() {
Vector3 yawForce = yawPower * (yawPercent / 100) * Vector3.up;
_rb.AddTorque(yawForce);
}
private void ApplyPitch() {
Vector3 pitchForce = pitchPower * (pitchPercent / 100) * transform.right;
_rb.AddTorque(pitchForce);
}
What am I missing?
Theoretically would movetowards or NavMeshAgent be more resources intensive
They're so fundamentally different it's not really possible to compare them.
MoveTowards is just a simple mathematical function. It takes in some parameters and returns a Vector.
NavMeshAgent is a component that handles navigation
It's kinda like asking whether the Pythagorean theorem or Google Maps is more resources intensive
Guys why does my detection happen before I'm actually on the object
if (Physics.Raycast(ray, out hitInfo, range))
{
if(hitInfo.rigidbody != null)
{
MeshRenderer objectMesh = hitInfo.rigidbody.gameObject.GetComponent<MeshRenderer>();
if (objectMesh != null)
{
objectMesh.material.color = Color.green;
}
}
}
wdym by on the object
also that ray might be hitting itself
use layers i suppose
can I post a scripting joke or is that not allowed
in 3D the ray ignores the collider it spawns inside of, so I doubt its this, but I also have no clue what the script and video is supposed to show in relation to what they said.
Anyone know how to create an AnimatorController asset and apply AnimationClip assets to it?
anyone know why hatebin doesnt make a link?
tried another browser ?
yes
ohhh is been a while since i had a raycast originate from the middle of char lol
public class DetatchChildrenOnDestroy : MonoBehaviour
{
public Transform[] selectedChildren = Array.Empty<Transform>();
public UnityEvent OnChildrenDetached;
private void OnDestroy()
{
foreach (Transform t in selectedChildren)
{
t.parent = null;
}
OnChildrenDetached?.Invoke();
}
}```
i have this small script that i'm using for VFX, mainly for detatching particle systems when it's parent gets destroyed so the particles can dissipate and destroy the particle system when the system stops.
However, i'm getting this message sometimes when i change scene
Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)
The following scene GameObjects were found:
EnergyParticles```
Is there a way i can avoid this, aside from well, not putting this OnDestroy?
So i have some structures and you can connect cables to do them. The connection points are fixed point on the structure. Whats a good way to move these points when i rotate the structure ? The problem is that when i rotate the structure i don't rotate it i change the sprite to another one. Should i store the position of each connection point for each of the 4 rotation or do something else ?
this is the strcuture btw and you can see it has 4 connection point
so it would be a tolta of 16 sets of coordinates
there must be a better way
my code is litteraly duck tape and glue, i can relate
Quick Q, I have a class and there are 2 instances in the scene. Class contains a coroutine with the following yield instruction, followed by some code
while (Time.time < some target) yield return null;
Let's pretend the coroutine's duration is 0.1 second. Instance A starts the coroutine, now 0.05 seconds later, instance B starts the coroutine, and now pretend GC kicks in/theres a spike for whatever reason and both coroutines end on the same frame. Is the code following the block above guaranteed to be executed in instance A first, or is that not guaranteed?
well from a logic perspective i would say that lag does not change the order of operation
but still i would not count too much on that
hm, ok well pretend 2 coroutines are called the same frame, on the same class and the same mono, is the first coroutine invoked guaranteed to execute its code before the second every frame?
When both coroutines yield every frame until condition X is met
https://www.reddit.com/r/Unity3D/comments/lc67a8/coroutine_execution_order/
Following the first answer i guess that the order is the same, but as they said here thats not something you should rely on, you function should work regardless of the exectuion order
any one got any idea ?
thank you @vague jolt
np
16 sets of coordinates really is nothing, but you could also just have a child object with those 4 points rotate instead. Not entirely sure how you are doing the connections, but at least by this way you wont have to differentiate between which point is which
thats what i did but they just don't rotate right
they are bit ofset from where they are supposed to be, still if you say to manually write the coordinates thats probably the best idea i guess
Since you change the sprites, the rotation might not be 100% lined up yea. The sprites you've shown look quite different and not like the same object rotated
Really it's just 4 collections of 4 points, assigning that is going to be way quicker and the memory used is so insignificant
ok thanks
So im trying to get KeywordRecognizer to work with a simple test, but it doesn't recognize anything i say, here is the code:
private KeywordRecognizer keywordRecognizer;
private Dictionary<string, Action> actionMap = new Dictionary<string, Action>();
private void Start()
{
actionMap.Add("up", test);
actionMap.Add("Up", test);
keywordRecognizer = new KeywordRecognizer(actionMap.Keys.ToArray());
keywordRecognizer.OnPhraseRecognized += OnRecognizedSpeech;
keywordRecognizer.Start();
}
private void test()
{
//Do something
}
private void OnRecognizedSpeech(PhraseRecognizedEventArgs speech)
{
Debug.Log(speech.text);
actionMap[speech.text].Invoke();
}
It never debugs anything...
look at your console to see the error
there is no error, it just never detects anything, i think it might have something to do with my headset. Dont know id it knows which microphone to use... But i have no idea how to fix it
docs are a bit light. You are on windows 10?
yes
did you check https://docs.unity3d.com/ScriptReference/Microphone.html? Maybe your device isn't recognized, or you need to start recording explicitly
i did consider that, but it doesn't mention anything about the microphone in the documentation and i also found a tutorial where i did the exact same.
maybe you should test it anyway, just to make sure your app is actually receiving microphone data to begin with
Yeah, i have tested the microphone and it does receive the data, i did that for an earlier attempt at voice commands
I do also have this warning in the build settings, but not sure if it is related
public class ConnectionsV2 : MonoBehaviour
{
[Serializable]
public class References
{
public List<GameObject> structures = new List<GameObject>();
public List<GameObject> cables = new List<GameObject>();
public List<int> connectedTo = new List<int>();
}
I have the class references in teh class ConnectionsV2
void deleteConnections()
{
foreach (KeyValuePair<string, ConnectionsV2.References> entry in connectionsV2.references)
{
foreach(GameObject cable in entry.cables)
{
}
}
}
Why for this i get the following error : KeyValuePair<string, ConnectionsV2.References>' does not contain a definition for 'cables' and no accessible extension method 'cables' accepting a first argument of type 'KeyValuePair<string, ConnectionsV2.References>' could be found (are you missing a using directive or an assembly reference?)
so how do iterate between the cables ?
get the value out of the key value pair
yes
pay attention to your types
foreach (KeyValuePair<string, ConnectionsV2.References> entry in connectionsV2.references
entry is a KeyValuePair<string, ConnectionV2.References>
Getting these errors and I dont really know why
I'm using URP and made a custom shader and its not working
my bad I thought that wasnt for errors
Blueprint saveStructure(List<GameObject> structures)
{
Blueprint save = new Blueprint();
save.entities = new EntityObject[structures.Count];
for(int i=0; i<structures.Count; i++)
{
save.entities[i].entity_number = i;
save.entities[i].name = structures[i].tag;
save.entities[i].position = new PositionObject();
save.entities[i].position.x = structures[i].transform.position.x;
save.entities[i].position.y = structures[i].transform.position.y;
save.entities[i].direction = structures[i].GetComponent<RotateSprite>().rotation;
save.entities[i].connections = new ConnectionObject();
save.entities[i].connections.first = new ConnectionPointObject();
}
return save;
}
Here i get this error
NullReferenceException: Object reference not set to an instance of an objectSaveFileGenerator.saveStructure (System.Collections.Generic.List`1[T] structures)
the error is on this line : save.entities[i].entity_number = i;
You have nothing assigned to save.entities[...], unless you're using structs
Yep^ Reference types (classes) default to null
So your array is full of nulls until you populate it
e.g. your code is expected to look like:
for(int i=0; i<structures.Count; i++)
{
EntityObject eo = new EntityObject();
eo.entity_number = i;
eo.name = structures[i].tag;
... // etc
save.entities[i] = eo;
}
(note rather than accessing it through the array a million times, you can just populate the object and then add it to the array at the end, as per my example)
I would also consider making a constructor for EntityObject like:
public EntityObject(int number, Structure structure) {
// populate all the fields in here, instead of externally
}```
then your loop can be even simpler. Something like:
for(int i=0; i<structures.Count; i++)
{
EntityObject eo = new EntityObject(i, structures[i]);
save.entities[i] = eo;
}```
isn't this save.entities = new EntityObject[structures.Count];
Yep^ Reference types (classes) default to null
So your array is full of nulls until you populate it
like i do that an now the variable exists, why can't i say this save.entities[i].entity_number = i;
how do i populate it ? isn't the code after doing it ?
ahhh i got it do i need to do save.entities[i] = new something ?
thanks
See the Script Loading Issues link pinned to #💻┃code-beginner
And don't cross-post
srry
Can you add some words to describe what we're looking at?
I just see a triangle and some numbers
which line
and wdym based on x axis
a triangle is not a line
this still doesn't clarify anything
what exactly is the information you have and what information are you looking for?
I know it seems obvious to you but we have no context
for what?
you are not explaining the issue well, hate to say
It is unclear in this picture what informatioin you are starting with and what you are trying to create/calculate
that makes no sense
You can't just say "I just want a function" without saying what you want the function to do lmao
cool story but like
what do you want the function to do?
just what?
lol
say what you are thinking
what is a "triangle like line"
that makes no sense
me neither
Imagine I said to you. Hey, I want a function that does this:
How do I do that?
you would have no idea what I'm talking about
that is what you have done to me
it's not the complexity
it's the fact that you didn't explain what you actually want
except for "triangle like line" which doesn't make sense
make which line?
maybe start by highlighting the line you are interested in
in the diagram
there are 4 black lines here
counting the dotted ones
there are two
and what do you mean by a "line" exactly? Do you want a vector? Or two points denoting the line segment?
two black lines
a math function needs to have some kind of result
I'm asking what kind of result you want
uhhh, no not in any universe is that one line lol
This is code, you have to represent your "line" in some way
you can't just say "a line"
I mean as far as I can tell all you want is how to make a vector with an x/y coordinate
and that's just new Vector2(x, y)
I feel like you are a robot sent here to confuse people
doing a decent job
first you wanted a math function now you want an image
soo you want to make a line between 2 points, then reflect that line?
Clearly I cannot help you
i didn't ask that at all
I asked what you want the math function to return
Actually I think what you want is this
well actiually
public float MyFunction(float x) {
return Mathf.PingPong(x * 2);
}```
that will give you the graph you shared
the dotted black line confused the hell out of me
ok sorry - idk your explanation was not grokking in my head
So ive been dealing with this issue today, whenever i create a script in unity, I always get the 'no monobehaviour in script' error. I re installed every version of unity including the hub and the issue persists.
even with an empty script
just to check, did you rename the script? Show it in your assets folder
i cant see the full name, but assuming you didnt rename it, do you have any errors in console
show your full console window
especially including the top right
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
omg i seriously didnt think to check it, thanks guys i just needed somone else to overview it lmao
"not work" is not anything we can help with
you have to explain what you want or expect the script to do, and what it's doing instead.
the script should change the skybox based on time it changes to the 1st skybox csRenderSettings.skybox = SkyNight; but it dosnt change from that
So what debugging steps have you performed?
Well, I see an error right off the bat so I doubt you aren't getting any errors in the console
is it the missing ; line 30? i fixed that
iv found the issue its restarting the blend for every frame
idk how else to handed it other than the if statment
Are there any errors?
Ok so I have a script that doesn't derive from MonoBehaviour but I want to see it in the editor to drag stuff in. Sure there is AddComponent() but it only happens at Runtime. Is there a way to "show" non-Monobehaviour derived classes in the editor? Or are there at least any workarounds?
Hmmm. It plain works
Might mess around a bit
Sounds like you want a serialized class? Something like:
[System.Serializable]
public class SomeNonMono
{
public int someNumber;
}
public class SomeMono : Mono //this could also be a ScriptableObject if it doesnt need to exist in the scene
{
public SomeNonMono data;
}
Otherwise, you may have to create a custom property drawer or custom editor with an attribute for that class and essentially tell the inspector how that class should be displayed when selected
AddComponent worked fine but I'll check out serialized classes. Thanks
Really? gameObject.AddComponent is usually only able to add scripts that derive from MonoBehaviour or Component or I think Object, how are you using it on a non-mono class?
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
Vector2 movement;
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Veritcal");
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
} ```
Hi, for some reason I keep getting this error when starting my game?
Veritcal
Really? I checked that several times to make sure it was spelled right.
Thanks for showing how idiotic I can be lol
strings are just tricky like that xD
Hi, I'm currently having an issue using the following package.
https://assetstore.unity.com/packages/templates/packs/dice-pack-light-165#description
I've looked through how it typically works, found the helper methods referenced in the READ-ME, but I believe that the pre-fabbed dice are invisible which I do not understand. I am somewhat of a beginner to Unity so I'm probably just missing something simple but the package had a helper method for rolling the dice which should've handled everything. I noticed that the clones do appear, however, they show as greyed out which I will show in an image below. I've even tried using some of their working demo in order to make it work and it simply will not show.
My code is as follows (made for a test outside of my main project):
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Dice.Roll("4d6", "d6-black", transform.position, new Vector3(1,1,1));
}
// Update is called once per frame
void Update()
{
}
}```
I've also attached the readme instructions for this asset in case anyone needs context: https://pastebin.com/gg7Ta1B9
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.
wait im so confused
when i use a check mark on them they show up
but why do i need to do that outside of my code
if you have access to the prefabs, try setting them to be active if they aren’t
they all appear to be active
huh weird
it's also strange because they included a demo scene which works fine, but even if I copy code to mine it won't work
I'm kinda frustrated bc I'm experienced coding in java and python in the past but i just cant get this to work
How can I get a reference to SRP feature of specific type?
Is there any way to show Sprite arrays in the inspector? I've tried [SerializeField] but that didn't work either. Am I missing something?
show your code and a picture of the inspector
Sprites should work so there’s something amiss
public Sprite[] spritesBlack = new Sprite[6];
public Sprite[] spritesWhite = new Sprite[6];```
hmm for whatever reason I had to handle the activity myself but it now works
are there errors in the console?
sorry lol they were hidden by warning messages
By default I always hide warnings, might be worth doing as well
yeah i should rlly do that, they never seem to say anything genuinely helpful lol
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
So I'm back and with a new issue so i beg for help, I cannot figure out how to check for which raycast would be closer, the idea of this code is to be the check for my AI if my player is close enough, however so that they don't detect my player through walls I added the hardplatform raycast but my issue is if the player is close to a wall or floor the enemies will not continue tracking the player. its in unity2D btw
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.GraphicsBuffer;
public class SC_AISensor : MonoBehaviour
{
public Transform PlayerTarget;
public float pDistance;
public LayerMask Player;
public LayerMask Hardplatform;
void Update()
{
}
public bool DetecManager()
{
Vector2 position = transform.position;
Vector2 target = PlayerTarget.position;
target -= position;
target.Normalize();
RaycastHit2D DetectBlock = Physics2D.Raycast(position, target, pDistance, Hardplatform);
RaycastHit2D Detection = Physics2D.Raycast(position, target, pDistance, Player);
Debug.Log(Detection.collider.tag);
if (DetectBlock)
{
return false;
}
else if (Detection)
{
return true;
}
return false;
}
}```
kinda unsure what you mean with this or what specifically the issue is, but for the
how to check for which raycast would be closer
https://docs.unity3d.com/ScriptReference/RaycastHit2D-distance.html
raycasts have the distance already so you can compare that
Why do you make two raycasts? Make one and check what it hits
i have to do two when using layermasks no?
in the inspector, doesnt it let u choose multiple options in the layermask anyways?
Yes it does
so should i take the layermasks out of the raycasts and have them in the if statement separately?
No, have one layer mask with both layers in it, and one raycast
whatever it hits will be the thing that was closest
I don't know too. Maybe that's Unity's issue. I am glad you have fixed it though
Hi. After I connected my project with git, any older files can't refer to the new ones.
i kinda wanna shoot myself in the foot rn
just found how to do what you meant
a lot of my code is much more cursed considering this is a thing
Works fine from the same file
git has nothing to do with it. Check if it compiles in Unity
Thank you so much @lean sail @mellow sigil @quartz folio
By looking in the console window and seeing if there are compiler errors
One of your scripts is in an Editor folder, so it's in the editor assembly
the other isn't, and cannot reach the editor assembly
I thought they all should be in global namespace
They are, the assemblies are different.
How to address this issue?