#archived-code-general
1 messages · Page 39 of 1
show me where you changed it and share the entire class again
also by doing this you're fucking yourself over in ways you clearly don't see
oh
lemme just link this again for you #archived-code-general message
maybe some day you'll actually listen
But Im not using it for the main part of it
then what is the point of it
Thats a good question
Just for getting if restrict is on and getting what the variables are set to
no wonder it doesn't work
Turns out im not actually using it
Does anyone know why this rarely gives a really small magnitude direction?
_minibossPos = Random.onUnitSphere.normalized * 40;```
It should give me a 2D direction of magnitude 40 right?
Sometimes I get values like (-1.8, 7.2) so clearly I'm doing something wrong
Is there a better way to get a random direction?
thanks that fixed it. What would be a better solution?
I started out with a Worldline type that holds different types (human, work, organisation) but since the language is slightly different (ie dob, dateFounded, etc) I'm finding I'm writing lots more code to process similar but not identical things. Guessing this is a well known problem and perhaps there's a much better way since i don't know what I don't know...
well until you show relevant code there's no way to know what you are doing wrong
lmao you're just constantly clearing the list any time you make a change in the inspector
that was supposed to go inside the if statements. you also didn't bother changing the first if statement's condition like i'd suggested
What was it you suggested
if (ItemType.Count != Menu.ButtonList.Count) this but for the first if statement too
This one?
yes
because, again. what happens if the list is larger than the count you are checking against?
well, you've wrapped the whole thing in the same if check - so you've now got 2 if statements doing effectively the same thing. too much indentation === not very readable.
so lets say you remove the outer if statement. now what would happen if you never entered any of your if statements? you would end up with a path that is Images/.png - which is obviously going to be a broken path
oh I can change the restrict bool now, I got rid of the new thing up top
you're not doing anything if none of those if statements are true so you'll be trying to access an invalid path, you should return or throw your own error in an else statement to prevent attempting to access an invalid path
You can improve what you have in several ways - but for starters, you have 3 isX properties on whatever "w" is. Why can't this be a state? something like w.Type, which returns an enum value of Human, Work, or Organisation.
Now, you could do something like this to handle errors properly
switch (w.Type)
case Human:
// do stuff
case Work:
// do stuff
case Organisation:
// do stuff
default:
throw new Exception("Unexpected type")
I'd even go a level deeper and say this should be a separate method that returns the string you're expecting. are you familiar with SOLID?
Ok great thanks will look into how to setup the w class with .Type
Guessing would do that for databinding then inject into a separate but common method
i haven't seen your code, but you shouldn't have to do anything nearly as complicated as databinding or DI to separate this out into another method
ok interesting thank you. The fileName example above iiuc is databinding because I'm building gameobjects from JSON so have to deserialize into a class and then bind those classes to gameobjects/attributes/etc and other processing depending upon what the player does... unless I'm missing something and there's another way here
How can I know which object / prefab does this refer to?
search for objects with that component in your hierarchy - it'll be one of your Text (TMP) GOs
in future, better naming of your GOs would help
im using urp and light 2d, everything works fine in the editor but when i build and run it, the lights dont work. are there any build settings i have to change?
not code question
In case anyone is interested, I made a fully modular menu navigation system for my game. Feel free to give any feedback or suggestions, I'm still working to improve it! At the very minimum I certainly want to add more and improve my comments. https://hatebin.com/vrvueorbmt
I also plan on removing some of the logs once I finish working on the script
I am trying to clamp the movement of the eye bones via a surface volume box, I am setting up the box and the eyes behave unexpectedly
I can show the code as well if anyone wants to take a look
Hi guys, I want to make an Android game where basically every time the user touches the screen he hits a little monkey/doll. How can I do to program this, that is, where do I start?
Hey is there a way to get direct lighting of the scene in a format that I can then read and determin the place in the world?
The place of what?
nvm sorry figured out I can do linecasts between the voxels and the lights to get direct lighting visability
Start with learning
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
sorry was away... yes I am
Whats the name of the website that allows you to paste code and share via temp link?
!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.
Legend thanks!
hi guys, do you recall if there is an callback for opening editor window? I would like to do something after timeline window is being opened
Hey, I have this code for making serializeable dictionaries, and I'm trying to use one in a ScriptableObject, but I am having this issue:
I can't set the length of the lists in the inspector, because it errors on validation because the list lengths are not the same... and I dont know how I can change the code to set them at the same time, or even just hard code in a set length for DictionaryOfIntAndSprite
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.
for (int i = 0; i < keys.Count && i < values.Count; i++)
this.Add(keys[i], values[i]);```
Is it true that this code is responsible for building verification? That's what chatgpt told me
I need to make a visual radius of where I can and cannot build
where would I put this? I'm mostly struggling with the syntax here
With the above, you'd get a a key-value pair if and only if a key and value both exists. Else consider filling with some default value if i is >= the length of values.
In your code where I copied it from..
With minor edit to the delimiter of the loop
sorry, honestly, this serializeable dictionary script is a bit of a black box... I wrote it after days of googling around on how to do a serializable diction and just barely got it working
You don't have much going on in the script. I'm sure you'll find it.
Why such a mistake?
How can I rotate my camera around a certain point in the world?
I want it to look like the camera is orbiting that point - kind of how you can rotate the camera in Don't Starve
It says the object doesn't have the component.
Special note: the compiler likely isn't wrong
It simply doesn't.. when the function is called.
With the above, you'd be able to remove the exception handling on different size collections as well. @unreal notch
help guys please
I don't understand how it works. I tried it with:
transform.RotateAround(Vector3.zero, Vector3.forward, 20 * Time.deltaTime);
However, it just rotates around itself, instead of around the world point of "Vector3.zero"
Don't cross post questions, stay in #💻┃code-beginner and wait for an answer there.
Get the world point relative to your object.
I tried implementing it, not working :<
I want to rotate around the "table" in the video, but you can see it only rotates around itself
why are you telling it to rotate around Vector3.zero?
It's just an example point in the world if I understand correctly
I thought it would look at Vector3.zero, and rotate around that point, while keeping its distance from it
Well your camera seems to be at 0, 0
if you want to rotate around the table then you have to use the coordinates of the table
The camera definitely isn't at 0,0. No matter where in the world I move it, it still rotates around itself
maybe Vector3.zero are some sort of local coordinates and not world coordinates?
I am trying to access different C# script that i made, but it doesnt want to find it in GetComponent<>(). with other scripts it works...
I'm guessing you have some other code that sets the camera position
does the name of the class match the file name exactly (including casing)? is that class perhaps in a namespace that you have not added a using directive in this file for?
the name is exactly same
and what do you mean exactly by the namespace?
looks like that file isn't actually in your project
it is in my project, and its even added to some emptyobjects already
i mean the file you currently have open. notice how it says "Miscellaneous Files" there rather than "Assembly-CSharp" close that file then double click the one inside your project to open it then make sure that you've spelled the name correctly
Thank you... This was the problem lmao
I'm trying to instantiate a world space TMP text gameobject to have pop up damage above enemies in 3D world space. I setup the prefab under the parent, save the prefab
when I instantiate the prefab instantiates off the parent, then is set as a child to that parent, but it's huge and not setup how I did making the prefab. anyone know what I should do for this?
guys how can i make a snake script where the tail follows the head?
ive done research but its all about the classic snake game
i am trying to make one where it moves freely
instead of only moving in 4 direactions
i tried storing them all in a list and then lerping the positions, it somewhat works but not the result i want
I imagine an approach similar to the 4 direction case would work
using the same approach makes it not smooth
maybe have a think about what you really want it to look like, and try to write down exactly what properties it should have
it sounds like you have something that sort of works but isn't quite what you want, you can tell it's not right, and might recognise when it is, but that's not too helpful in making progress in building it
This file is not part of the same assembly that Unity compiles your project in. Not sure how you managed that, but it will probably be fixed if you remake this file.
How can I calculate the final position of moving a child to a point and then also moving the parent with relative offset?
I've tried doing position = target.position - parentvariable.position
but it doesnt seem to be 100% accurate
that's a confusing statement. could you provide more context on what you're trying to do?
Basically I want to automate a gun's ADS positioning by moving the iron sights to the centre of the screen and having the parent move with it
how about lerping?
i can already set the position manually
and it works
but i want to try automating it
just need to find the correct position
thats alright, thanks
that might work
but surely theres a way to calculate it all into a neat vector3 variable lol
Why don't you calculate the parent movement and the child be be just moved?
Other than this sure you can do:
- store child global position before movement
- move the child
- calculate global position delta (new - old)
- move parent with the delta
- set child local position to the initial local position in parent
However, sounds pretty bulky solution
hmm
If the local position in parent variates, you can introduce step 0 where you store that too
thank you, ill look into what you said
aswell as some further testing
if i were to make the the parent the child
would the new parent then have to be the location of the sights?
sights? what do you mean?
I use Pascal case for public fields and methods. Camel case for private fields and variables.
I have to admit I am using the Java camel case notation, so starting with lower case. however in C# I think starting with upper case is rather the standard.
nevermind i just got it working
i was overcomplicating it alot before
well, congrats 🙂
thanks for the help
sure
I have just upgraded Unity from 2021.3.1f1 to 2022.2.6f1 and I face a very weird behavior: adding force seems not to work any more somehow? The code below is super simple and worked flawlessly with the old version.
The print statement is executed, force is added (vector is not zero) and still the velocity always stays at 0 (as printed in next update run).
I already tried with adding relative or not relative force, as well as changing the force types to impact, velocity, etc - always zero velovity on next update.
void Update() {
if (accelerate && (rb != null) && (rb.velocity.magnitude < maxSpeed)) {
print("a++: " + rb.velocity.magnitude + ", force: " + (Vector3.back * maxSpeed * Time.deltaTime)); // TODO: rem
rb.AddRelativeForce(Vector3.back * maxSpeed * Time.deltaTime, ForceMode.Impulse);
}
}
rb comes for rigidBody
Any ideas?
hm
quick check if you accidently set the rigidbody to have no gravity or iskinematic
and if it worked in a previous version i'm not sure why it wouldnt be working now
I'm having a bit of a brainfart on a solution for this. I have an isometric camera that rotates around a small scene. The walls are planes, so I can see through the backfaces (intentional) but I intend to have objects on the walls that I would like to hide when the walls are occluded. (see screenshot for example). Any ideas?
yeah, same here... i am kinda clueless... is so simple code and stopped working out of the blue...
is not kinematic, no gravity and also not frozen
hi I have a question. say I have a game object A with a unity event on it and another game object B is subscribed to that event. now if game object A is destroyed do I still need to unsubscribe game object B from A's event? cause I don't think I could get a reference since it's now destroyed
You can use Raycast (or some other physics query) to check the occlusion.
Turn on Physics.queriesHitBackfaces when you perform the cast, or use MeshColliders with two-sided meshes.
I have a smart string and want to replace it in code, I tried:
string wrTime = "test"; LocalizationSettings.StringDatabase.GetLocalizedString("Game", "SHOWING-WR", new string[] { wrTime }
and
string wrTime = "test"; LocalizationSettings.StringDatabase.GetLocalizedString("Game", "SHOWING-WR").FormatSmart(new { wrTime })
but both dont work
so I set it to "Maintain Tokens" and LocalizationSettings.StringDatabase.GetLocalizedString("Game", "SHOWING-WR").FormatSmart(new { wrTime }) now works. I dont know if its bad to do it like that but it works
!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.
Suggest you debug the values in the if statement and/or check if the if statement is entered at all
As I wrote above - the statement is executed and the print statement shows continuous velocity of 0, while the force variates a bir as it is depending on Time.deltaTime
guys this error is popping up even tho im not using a custom editor
type is not a supported pptr value
And was working without any changes before the upgrade to 2022
- forces should always be added in FixedUpdate not update
- you should never multiply your force by deltaTime
- you should show the inspector for your script since you have locked your AddForce behind an if statement and are using this maxSpeed variable
Thank you! Will try it out immediately. Yes, if in fixedUpdate deltaTime is not necessary.
What do you mean with the last point?
With the last point I mean you should show the inspector
If maxSpeed is too low or zero ot won't work
If acceleration is false it won't work
Etc
Ah, got it. No, the syatements are all executed - the print is inside the check
You are also kinda weirdly doing double duty with this maxSpeed variable. It's both the speed limit and the force amount
True. I will have to change this, especially now that deltaTime is not used - it was naturally/steady reducing the added amount
can I use a custom index.html for a webgl build?
I have a list that is randomized every time there is clicked on the screen, and you fill the content of the list in the inspector for example
Element 0: Everyone do this
Element 1: <name> do this
But I want it when every time the <Name> element is mentioned in the sentence it will get a different color.
Anyone know how to make it
Same behavior after moving it to FixedUpdate: velocity is always 0, added force is 0/0/-1600
now constant after Time.deltaTime is gone
There's probably just an object blocking it
It's a space simulator - nothing there... no floor, no walls... no objects around...
I am getting crazy...
one sec
I am not sure if this question should be posted here or in an other channel; I am trying to work with the Test framework, but in my unit test I can not access anything form the Assembly-Csharp project and I cant force the buildpath to build the UnitTest project last. Does anyone have an idea how I can fix this?
Did you create assembly reference for your scripts ?
You need to set up your assemblies properly
Where can I do that?
You need to make an asmdef for your main game code
Just watch one tutorial about unit testing and that's all
And reference it from the test assembly
I did watch one :) but I guess it was 100% complete
Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP
In this video I'll show you how to write more effective Unit Tests in Unity. More importantly, I'll demonstrate how valuable Unit Tests can be for Unity projects of any size and Unity developers of any skill level.
#Unity3D #UnityTutorial #GameDevelopment
📦 Download the co...
The yellow fire things are the "bullets", which are not moving any more. On the right is the prefab config. The actual code making the movement is in PlanetDesctructionBullet, which I (most of it) pasted above - the one with the FixedUpdate
Why is it saying these don't exist?
I did have to launch my project in safe mode after upgrading it to a later Unity version so that could be why. I'll try load it normally
- Your movement script inspector is not visible
- You've hidden the whole scene hierarchy
Sorry for this :/ One sec, have to do slight code change, so that the bullets do not disappear and i can make the screenshot
This happens from time to time on upgrade, just reimport assets and restart normally
Thank you!
Does anyone know why I am getting this error? I did not change anything and all scenes are in the build settings?
What is the best way of copying all property fields in a constructor when there are a significant amount of fields?
I'm finding propertyname = x.propertyname is getting hard to maintain.
The class is not fully serializable as I tried serializing and deserializing with Json which did not work
This is the hierarchy, script is coming in a sec
If you set up your Visual Studio correctly, you can select your class, and select "Create constructor" or something when you open quick actions
Then you can specify the fields/properties to implement
If it generates in a practice you don't like, you can specify the way Visual Studio auto generates public/internal/private fields/properties in the options
anyone knows?
You should always make sure that any existing subscriptions are removed using an OnDestroy method
but if my object isn't destroyed it'll never call OnDestroy? so should the one I'm subscribing to, aka the object that'll eventually be destroyed, somehow clear its own event from listeners?
Not sure actually. I would assume that Unity has some sort of garbage collection to ensure the script is cleaned up when the gameobject is destroyed
in my example, object A with the event will eventually be destroyed at some point. but object B, my object won't be destroyed. but I'm wondering if even after object A is destroyed if the link will still exist in memory
You can always do the same in the parent, but then set the event reference to null
Because this could be a reference that causes garbage collection to not work, and setting it to null removes that reference
Probably best to look up how that works
problem is I can't access the event if the gameobject is null
im trying to reload current scene using
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
but the scenes go into a loading/unloading loop
Because that code loads the scene its currently in, if you don't have some sort of check/action to call it, you will always loop.
why does it return negative values?
!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.
maybe this thread helps? Seems like they are just saying to do a null check(see praetor’s message at the very bottom) https://forum.unity.com/threads/c-event-unsubscription-when-object-is-destroyed.1255197/
cos of angles between 0 and 90 should only return positive values, no?
float randomAngle = Random.Range(0f, maxOffset / 2);
if (Random.Range(0f, 1f) > .5f)
{
offsetVector.y = Mathf.Sin(randomAngle);
}
else offsetVector.y = -Mathf.Sin(randomAngle);
offsetVector.x = 1 - Mathf.Cos(randomAngle);
Debug.Log("cos: " + Mathf.Cos(randomAngle) + " angle: " + randomAngle);```
why does the cos return negative values
this is in radians
Mathf.Cos uses degrees no?
and pi/2 in degrees is 90
so it should only return these values
Well I'm not 100% sure, but it looks like its doing what I posted in the graph.
it works with angles
It uses radians
what’s maxOffset?
why does literally everything say angles
Look at what MJ just sent
yes if i put, say, 180 into it, it should give me -1
The input angle, in radians
ffs why doesn't it say "radians" in docs then
Wdym, it does
alr ty
mb i didn't see that
Btw Mathf.RadToDeg and Mathf.DegToRad exist for convenience
the reply from the OP to the first comment is the exact issue. adding a null check does nothing for me when I already know the gameobject is null. that's the same as doing nothing. cause no matter what it would still be null cause it's destroyed because my object ever is
Did you read Praetor's response there, like Pumpkin suggested?
yes? it's a nullcheck? and I'm saying that's not gonna solve anything when I already know the object to be null. I don't need to check to know. the object will always be null at the given point before I can unsubscribe
they do mention that there shouldn't be any risk of memory leaks so I'll take that as the garbage collection cleaning up the loose ends
Well events are weird so idk if Unity is smart enough to realise the event is no longer valid
Not sure if the build in Event types fix that
General rule is to always somehow unsubscribe if you're certain you are losing the reference due to destroying it or whatever
looking at it, it is actually an Action I'm subscribing to. so it should be handled by C# itself
You don't subscribe to delegates, you assign
So if you mean you assign to it, then yes, it's garbage collected
If i want to use scriptable objects to keep data between scenes, can i use new/instantiate or do i need to have a "physical" asset of the scriptable object that I reset everytime i need to reset it? Honestly I have never used new/instantiate with SO so idk how it works
Edit: i think using actual assets might be better idk
Any idea about the adding force problem above?
Inho scriptable objects should not be used for mutable data at all. If one scene relies on data from the previous one what I suggest a data manager using the singleton pattern
Ask it again?
Or reply to your question or something
I saw this one video mentioning that one of the sole purposes of using SO is to have data between scenes. Sure singleton is an option, but since I only need to use my SO between 2 scenes and it will always get reset in one of them anyway (since I'm not keeping any permanent data) it seems simple enough just to use that
I am having a space simulator, so free space without any objects nearby. I am firing "bullets" by AddForce. Everything worked great with Unity 2021.3.1f1, however then I needed to upgrade to 2022.2.6f1. Without any code change the "bullets" do not move any more. Code is executed - I added print statement just before adding the force, however the velocity remains 0.
here are the details:
First screenshot shows the bullet prefab config, the second the script which should move the bullet
Looks like you are dealing with super large numbers... What if you try with a number that is not half a million (maxSpeed)?
let me try
same thing: fixed upd: 0, force: (0.00, 0.00, -1.67)
first zero is the velocity
this is with max speed 50
Hmm. What íf you rebuild the object from scratch?
Like make a new empty object, add each component to it and see if it works
@night relic Also put the log after the AddForce, not before
How can I code this and can Unity do it ?
Convert the bone's position to that object's local space with InverseTransformPoint
Clamp it
Convert it back to world position with TransformPoint
Apply the position back to the bone
Ok, thanks, will try to recreate and post again. Is really weird, is such a simple thing... and not working... mind blowing
using UnityEngine;
public class EyeControl : MonoBehaviour
{
public Transform headBone; // the head bone object
public Transform leftEyeBone; // the left eye bone object
public Transform rightEyeBone; // the right eye bone object
public Transform leftEye; // the left eye object
public Transform rightEye; // the right eye object
public Transform target; // the target object for the eyes to look at
public float eyeOffset = 0.1f; // how much to offset the eyes from the bone position
public float maxLookDistance = 10.0f; // the maximum distance that the eyes can look at
void Update()
{
// get the head bone position and rotation in world space
Vector3 headPosition = headBone.position;
Quaternion headRotation = headBone.rotation;
// calculate the eye positions based on the target object position
Vector3 targetPosition = target.position;
Vector3 leftEyePosition = targetPosition + (headRotation * Vector3.left * eyeOffset);
Vector3 rightEyePosition = targetPosition + (headRotation * Vector3.right * eyeOffset);
// Lock the Z position of the eye bones
leftEyePosition.z = leftEyeBone.position.z;
rightEyePosition.z = rightEyeBone.position.z;
// set the positions of the eye bones
leftEyeBone.position = leftEyePosition;
rightEyeBone.position = rightEyePosition;
}
}```
@hexed pecan
So do I do that here inside my script ? I know how to add the public variables but I don't know how to make the clamp happen according to the targets in those fields which would be the meshes of the eye cages
Doesn't look like youre doing what I explained
@hexed pecan
Of course I am not because i do not know how to which is why I am asking, I am able to take it here so that I can add the meshes
But then I do not know how to tell unity to use those fields to clamp the movement for each bone
You don't know how to what
How to tell unity to use those fields to clamp the movement for each bone (according to the screenshot I just showed you)
Be more specific
Give me a moment
Vector3 boneLocalPosInCage = cage.InverseTransformPoint(bone.position);
boneLocalPosInCage.x = Mathf.Clamp(boneLocalPosInCage.x, -1, 2);```
etc.
And you would apply it back with bone.position = cage.TransformPoint(boneLocalPosInCage);
@hexed pecan
Actually if you want to limit the iris to that outlined area, I would just do it with a shader
Have the iris on a texture and just change its texture offset
So you would have a mesh for each eye like the cage currently is (outlined) and just move a texture on it
And can I still control that offset using the eye bones so that I can have the character look at ? Plus if I do that I also want the iris to go a bit "outside" that outline just like real eyes do sometimes
Yes you could get the eye bone's position and send that to the material/shader
hi, I've got this code to pick a random tile in my tilemap and return it's name, but it's just saying the object is null. It worked for about two test runs and then refuses to work now, nothing changed in between.
new to tile maps so I can imagine I'm doing something wrong but extensive googling hasn't helped 😛
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.
What type of shader should I use for this ? (I am using URP)
Honestly any shader can work as long as it has an exposed offset/tiling property
also sorry for the popping in that video
Can try with standard shader first
Maybe with alpha clipping enabled, unless you add a white background to the eye
Gotcha, I don't think I will add a white background as of yet but that's good to know for the future if I want to add one.
ok now on some runs it works and some it doesn't
Thanks, this was a bit better than doing it manually!
For anyone who has this same issue: You must either use yield on the manager.Initialize function since it returns an IEnumerator, or invoke it using StartCoroutine if you're not calling it from inside another method that returns an IEnumerator.
@hexed pecan I just realised that complicates the customization part of my character creation process as now I'd need to swap textures around each time the user changes something to the eyes
I'd prefer using my texture atlas and no other texture
Why would you need to swap textures around?
Because I am using a single texture atlas for all the custom choices when it comes to how the clothing and the eyes colour looks like, having the iris as a separate texture would complicate the system too much
This is the reason why I had the eyes as actual meshes instead of textures
So that I can still use the same texture atlas to swap the eyes colour around
Idk then. Look at tutorials on "cartoon eyes" im sure youll find something that works for you.
I tried, nobody does what I am doing
Apart from the first solution that I said but apparently that doesn't fit your needs
I'll try the first solution
this one
https://pastebin.com/E3t8vy41 so i am trying to make a pathfinding solution,but it seems that i am doing some calculations wrong (specificallu line 15-20 and line 196),here is a video explaining the problem and an image explaining my goal
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 added option for players to move the 3D camera to the sides. However I want to limit it, but since the camera is rotated, I dont know how to calculate limits since its moving on multiple axis. Any math genius?
aka only want the camera to be able to move in perpendicular direction to where it's facing
Can anyone tell me why
using UnityEngine;
using UnityEngine.Events;
public class OnLayerDoX : MonoBehaviour
{
public LayerMask layerMask;
public UnityEvent layerEnterCollision;
public UnityEvent layerExitCollision;
void OnTriggerEnter(Collider other)
{
if ((layerMask.value & (1 << other.transform.gameObject.layer)) > 0)
{
Debug.Log("Hit with Layermask");
layerEnterCollision.Invoke();
}
}
void OnTriggerExit(Collider other)
{
if ((layerMask.value & (1 << other.transform.gameObject.layer)) > 0)
{
Debug.Log("Left contact with Layermask");
layerExitCollision.Invoke();
}
}
}
Wouldn't even show the debug log.
The objects have layers and colliders, the object hitting the specified layer has a rigidbody and trigger collider but nothing happens?
- Validate
OnTriggerEnterhits. - Validate
(layerMask.value & (1 << other.transform.gameObject.layer)) > 0returntrue.
Sorry no formal training, what do you mean by validate?
Validate = check
Check if these are the case
Wouldn't that be the point of Debug.Log("Hit with Layermask");
void OnTriggerEnter(Collider other)
{
Debug.Log("OnTrigger Valid");
if ((layerMask.value & (1 << other.transform.gameObject.layer)) > 0)
{
Debug.Log("how would I check layerMask.value?");
layerEnterCollision.Invoke();
}
}
Neither of those logs show but the object is clearly resting on the desired layer?
Any help?
I mean could you draw a raycast to the point see if there’s anything in front of it and if not move in the direction of the raycast
Also what is the most useful thing (in unity c# of course) functions, statements, etc
the problem is not that
If not even the first log shows then the layer isn't relevant, it doesn't even get that far to check it. Something is wrong with the setup, show screenshots of the inspectors of this object and the object that it's colliding with
@hexed pecan I'm almost there, but there seems to be an issue with the Z position when the eyes move to the right, did I clamped the positions wrong ?
using UnityEngine;
using UnityEngine.XR;
public class EyeControl : MonoBehaviour
{
public Transform headBone; // the head bone object
public Transform leftEyeBone; // the left eye bone object
public Transform rightEyeBone; // the right eye bone object
public Transform leftEye; // the left eye object
public Transform rightEye; // the right eye object
public Transform target; // the target object for the eyes to look at
public float eyeOffset = 0.1f; // how much to offset the eyes from the bone position
public float maxLookDistance = 10.0f; // the maximum distance that the eyes can look at
void Update()
{
// get the head bone position and rotation in world space
Vector3 headPosition = headBone.position;
Quaternion headRotation = headBone.rotation;
// calculate the eye positions based on the target object position
Vector3 targetPosition = target.position;
Vector3 leftEyePosition = targetPosition + (headRotation * Vector3.left * eyeOffset);
Vector3 rightEyePosition = targetPosition + (headRotation * Vector3.right * eyeOffset);
// Lock the Z position of the eye bones
leftEyePosition.z = leftEyeBone.position.z;
rightEyePosition.z = rightEyeBone.position.z;
// set the positions of the eye bones
var x = Mathf.Clamp(leftEyePosition.x, -0.0072f, -0.0544f);
var y = Mathf.Clamp(leftEyePosition.y, 0.0683f, 0.0786f);
var z = Mathf.Clamp(leftEyePosition.z, 0.0955f, 0.0711f);
leftEyeBone.localPosition = new Vector3(x, y, z);
rightEyeBone.localPosition = rightEyePosition;
}
}```
The clamping is correct for other positions
Thank you
Could it be the collision matrix?
When I press play the torque wrench is set to grabbable layer.
if ((layerMask.value & (1 << other.transform.gameObject.layer)) > 0)```
This isn't quite a correct check btw.
```cs
if ((layerMask.value & (1 << other.transform.gameObject.layer)) != 0)``` would be correct
(to see if the layer is contained in the mask, assuming that's what you want)
Hmm. That doesn't seem to work either. I think its right but I must have something else messed up in my scene?
Help please
Have you checked if the method enters at all?
At first glance you have an index out of range. I can look more in a few minutes.
I don't think it is. I'm going to test with some other layers. Thanks for your help!
A couple of things that might cause it:
- the wrench has a Rect Transform, is it a UI element? That won't collide with "normal" objects
- the sphere collider radius is tiny
the layer has nothing to do with it if the event doesn't trigger
Guys if anyone can help me on this one it would be very much appreciated
(in local space)
The eye does not go outside the face for the minimal clamping values (even if I change those values it seems to stay in local space) but for the other values it goes beserk, it seems to get out of the local space into global space and I don't understand why that happens.
(the values inside the rectangle are the minimal clamping values)
https://hatebin.com/aubjunnaqq
Hey there! I'm probably just going mad, but for some reason I can't get buttons to work with my controls script. I have a script which is basically empty with some variables and functions. However, when I set my "Controls Logic" up in my button, no functions show up. Is there something I have to change with the the code or unity to make it see these functions?
The functions can have at most 1 parameter for them to show up there.
your functions must be public and must not have too many params or unsupported params
That would explain it, thank you
I suppose I would need to make a separate set control function for each button then, no?
Never mind, I think I have an idea
done yet?
I'll just add a SerializeField in my Controls Logic gameobject for each text object on buttons
hi, i just wanted to ask what the best way to do asynchronous file operations is. can i use the System.IO namespace, using FileStream objects in IJob implementations?
i'm having an open world system where the player needs to save and load world data from files as they walk around
please @wet knoll if you have an answer for me
how can I restrict movement of an object to a plane?
Well it depends what you mean. Are we talking about a physically simulated Rigidbody, or jsut an object you're moving via the Transform
if it's the latter, simply don't move it except on the two axes of the plane
its a Camera, i want to move it perpendicular to where its facing
but since its rotated, i cant just use X/Z axis that easily
sure you can
you can use the world x/z
yeah but Im a math idiot haha
// Camera movement with mouse
Vector3 diff = (cam.ScreenToWorldPoint(Input.mousePosition)) - cam.transform.position;
if (Input.GetMouseButton(0))
{
if (drag == false)
{
drag = true;
dragOrigin = cam.ScreenToWorldPoint(Input.mousePosition);
}
}
else
{
drag = false;
}
if (drag)
{
transform.position = dragOrigin - diff;
}```
that works just fine but if I want to limit the movements, im not sure how to calculate it
(that code is inside LateUpdate)
you can do var displacement = gameObject.transform.rotation * Vector3.forward * distanceToMoveItPerSecond * Time.deltaTime;
is this using an orthographic camera?
yes
Any idea what to do?
You are mixing world positions and local positions here... Why not do it like i showed with InverseTransformPoint+TransformPoint?
Sorry I had to hop on a call.
Say a component is enabled by another component at runtime. Will update in the former be called the same frame it was enabled in 100% of the cases, or does it follow some internal script execution order and if the latter component runs after the former, then it'll wait until next frame to call update?
it depends on when you enable it
😄 thats what I was gunna say.
if you enable it in Update I think it's guaranteed not to update this frame
if you enable it in FixedUpdate then it might?
I'm not 100% sure
Okay, doubt is good enough of an answer for me either way
Basically I think it would have to be enabled before Update in this game loop diagram: https://docs.unity3d.com/Manual/ExecutionOrder.html
but even then it might just always wait till next frame. Worth experimenting with Time.frameCount if you want to be sure
easy way to do it would just check if the component is active, if not wait a frame and try again
probably not best solution...but certainly the easiest
how do you have so many bools in there
Hello fellows creators, I have a simple question: I want to have access to my UI scripts and methods, should I use singletons on menu scripts or make a script that contains all my menu scripts?
depends how many instances you’re going to have of said script, i think
The sphere collider should be big enough. The Rect transform was for the digital display but was not needed on that object level and has been removed. The event can be triggered manually.
there’s something bad about using singletons, if that means static, i think i saw someone use singleton in place of static
"the event" = OnTriggerEnter
That's why I'm wondering
it’s either multiple things named the same or multiple instances
more like it has a time and place, they are great when done correctly
I don't have a lot of menus yet, but if the UI progress I will add menus with each having a script
yea
idk if either is the case probably don’t use it, unless you can find out for sure
I have everything thats a singleton in some sort of fancy script thing that creates Don'tdestroyonload when the game starts reguardless of scene or anything 🙂
no chance of doubles or anything
Maybe it's better to make a scripts containing all my menus in a scene, it's only one singleton and this one knows all the UI elements
is there a way to save a what a variable is set to, for variables changed in the inspector, even after closing unity?
Yes, you have to use the PlayerPrefs
oh god not that
I did it for my options : PlayerPrefs.GetInt("FPS") and PlayerPrefs.SetInt("FPS")
Well not that much solutions, maybe you can create your own saving system with a json
i haven’t dealt with actually creating files through a script yet to save things
or in general
Sorry I thought you meant the unity event public UnityEvent layerEnterCollision;
There’s a ton of PlayerPrefs tutorials on YouTube. I would only use this for saving settings though and not the actual game data
Yea
I think I understand how it work
Can anybody help,or at the very least tell me a how to fix it?
Have you looked at the index that was out of range?
@devout solstice It's pretty easy used this way, and it works but you need to "load" where the game starts
it gives me nothing of help
What happens if you remove [BurstCompile]?
why is everything red
it's an editor tint
@leaden ice Another question if you dont mind, according to the unity docs the point1 and point2 of capsule cast are the center of the sphere. This means that if i place point1 at transform.position of the player(this being the ground) the capsule will be slightly under the ground because transform.position will be the center not the bottom
how do I make sure the capsulecast bottom starts at exactly the same position as the player that sending it (meaning it will just be around the player and not slightly underground because of the above
Its to help him know if its in play mode and not try to make updates before stopping play mode.
do I just add an offset to it? is there a proper way to know this offset or just trial and error
ohhh
How can I use RotateAround, but lerp it? I want my camera to rotate by 90 degrees each time a key is pressed, but smoothly ease in and out instead of doing it instantly.
set the thing you’re trying to move to a variable then put that variable into rotate around and set the rotate around to a variable, then lerp that variable and set the objects position to that variable
maybe
idk i think that would work
Thank you, I did try and it works a bit better now (the eyes are starting to move smoothly now but it still clips.
using UnityEngine;
public class EyeControl : MonoBehaviour
{
public Transform headBone;
public Transform leftEyeBone;
public Transform rightEyeBone;
public Transform leftEye;
public Transform rightEye;
public Transform target;
public float eyeOffset = 0.1f;
public float maxLookDistance = 10.0f; // the maximum distance that the eyes can look at
void Update()
{
// get the head bone position and rotation in world space
Vector3 headPosition = headBone.position;
Quaternion headRotation = headBone.rotation;
// calculate the eye positions based on the target object position
Vector3 targetPosition = target.position;
Vector3 leftEyePosition = targetPosition + (headRotation * Vector3.left * eyeOffset);
Vector3 rightEyePosition = targetPosition + (headRotation * Vector3.right * eyeOffset);
// Lock the Z position of the eye bones
leftEyePosition.z = leftEyeBone.position.z;
rightEyePosition.z = rightEyeBone.position.z;
// convert world space eye positions to local positions
Vector3 leftEyeLocalPosition = leftEyeBone.InverseTransformPoint(leftEyePosition);
Vector3 rightEyeLocalPosition = rightEyeBone.InverseTransformPoint(rightEyePosition);
// set the local positions of the eye bones
leftEyeBone.localPosition = leftEyeLocalPosition;
rightEyeBone.localPosition = rightEyeLocalPosition;
// clamp the position of the left eye bone
Vector3 clampedPosition = leftEyeBone.localPosition;
clampedPosition.x = Mathf.Clamp(clampedPosition.x, -0.0102f, -0.0539f);
clampedPosition.y = Mathf.Clamp(clampedPosition.y, 0.0567f, 0.073f);
clampedPosition.z = Mathf.Clamp(clampedPosition.z, 0.0946f, 0.0716f);
leftEyeBone.localPosition = clampedPosition;
}
}```
it became more readable,but i still can't figure it out
does the value need to be negative?
does the max number need to be positive
positive
i don't decide the value,the position calculation does it for me
oh
Make sure the eye (cages?) mesh corresponds to its rotation
what if you make it not negative
if that doesn’t work try making it so the max number is -16 instead
My bad there, the cages are basically the eye sockets, bad naming there on my side.
The error message indicates that the index "{0}" is out of range of the sequence "{1}". This can happen if the code is trying to access an element of a list or an array using an index that is larger than the length of the sequence. the index might be out of range in the line print(names[2]) if the names list has less than three elements (i.e., if it has an index from 0 to 2). The error at line 97 could just be stopping at that line but seeing an index in any of the int2 before it.
So basically rotate the mesh in a 3D software so that the object's forward axis is aligned to the surface
Looks like its currently tilted
i followed a tutorial,and it seems to work when given precise int2 inputs,but when i try inputting vector2 inputs it doesn't work
hello,
i have a prefab which i want to instantiate multiple times (asteroids)
is there a way to dynamically read the size (bounds.extents) of the prefab?
it return Vecto3.zero
maybe something like
GameObject prefab = // your prefab game object
Vector3 prefabSize = Vector3.zero;
Renderer prefabRenderer = prefab.GetComponent<Renderer>();
if (prefabRenderer != null)
{
prefabSize = prefabRenderer.bounds.extents;
}
Debug.Log("Prefab size: " + prefabSize);
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=1bO1FdEThnU
Let's implement Pathfinding in Unity DOTS, we're going to write everything in a Data Oriented way (Structs) in order to benefit from massive performance!
Here's the follow up video covering Pathfinding in Unity ECS
https://www.youtube.com/watch?v=ubUPVu...
is the resource folder a bad thing to use?
ive seen some stuff online about how you shouldnt really use it too much but its kinda required for my project
Yo I don't have time to watch a 6 minute video
why not
Text is always better
Lol I just realised I rambled for 6 minutes
My bad
If your using A* algorithm why do you need to change to vector 2? (I have not watched the whole video busy with multitasking other things).
Long story short: I am not supposed to do anything on the eye meshes because they simply follow their parents (the bones) and the bones were already oriented using the normal of the eye socket in Blender, the bones have the correct orientation otherwise when I'd move them in Unity in their local space they'd clip out but they don't.
oh yeah that worked. wierd i could swear i did do exactly that yesterday evening
can someone explain this
@hexed pecan
how would i go about making a game view in an editor window ? i'm trying to make a custom tileset editor, that includes triggers and spawnpoints for various objects
(the triggers would be objects and the tiles would be tiles, im just not sure how to mix both without having to make a separate editor for it)
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
i guess it'd be better to have a scene view, since in game view you can't move the camera around
ah ok thank you
Lets say you have object eye.
Now lets say theres another object socket, which is rotated so that its forward axis faces outwards (where an eye would look).
To clamp eye's position in the space of socket, you first convert its position to socket's space:
var eyePosInSocket = socket.InverseTransformPoint(eye.position);```
Now you can perform clamping, lets clamp it in the X for example -0.01 to 0.01 range:
```cs
eyePosInSocket.x = Mathf.Clamp(eyePosInSocket.x, -0.01f, 0.01f);```
Now convert it back to world space and apply it to eye:
```cs
eye.position = socket.TransformPoint(eyePosInSocket);```
@whole portal
Up to your project scale
I use it purely to create Don'tDestroyOnLoad objects once when the game starts
so it can have negative effects?
How can I check that because when I do select the eye socket in Unity the 3 arrows won't display so I don't know which is pointing where
If you are at the scale that you need to worry about how much memory the resources takes, or having to patch you resources with live-ops operations then yes, Resources folder has it’s limitations
The pivot is probably somewhere else. Change your gizmos from Pivot to Center mode and you should see the arrow there
wait so resources are always loaded or something?
So is this the socket selected?
yes
my issue is just with the amount of stuff in the resource folder
Resources bundle (the compressed form) is always loaded not individual resources
The eye bone seems to be okay though
oh ok
What is the "eye bone", is it what the eye follows?
yes
yes
Btw it also looks wrong
but I am not using the sockets at all in my code, I just have them inside Unity
Blue should look forward
I haven't talked about the bone at all in my explanations
It's about the socket and the eye
The reason I am not using the socket is because they will not be animated, I'll be using blend shapes for eyes (sockets) opened/closed and I am using the eye bones only for moving the eye mesh.
Whatever you call it, you need an object that represents the plane that your eye is allowed to move on
Then I can use the eye sockets for that
Thats what I was saying?
At first
I dont really care what you call it
Oh I see
So how do I fix the blue arrow for the bones do I just reset all the transform of the eye bones inside Blender an re-import the model ? I wanted to do that but I was afraid not to lose the local orientation information of the bone in the process.
Yes fix it in a 3D modeler as I said
The code you showed also looks nothing like what I suggested
This is how the eye bone orientation looks now, I performed a reset on all transforms of the rig. @hexed pecan
Everything but the eye bones works like you said after resetting the transforms on everything. I don't know why the eye bones appear to be facing downwards in Unity.
I did check the apply transform box as well but still the same result
Question, Allocator.TempJob from NativeArray<T>, the documentation says it last 4 frames... so...
Is it 4 frames including the frame which called the constructor of the array or 4 frames after that frame?
And, does the allocation becomes invalid at the start of the last frame, or at the end (start of the 5th)?
And then if I manually change the rotation in Unity then it meses up the iris mesh @hexed pecan
presumably you knopw where your object's pivot is in relation to the ground. The offset is the capsule radius
if your character's pivot is touching the ground then the offset would be exactly equal to the capsule radius
If your character's pivot is in the center of the character or something then you'd do the height of the pivot minus the capsule radius
Anyone have any experience or know if its possible to use a development server (ReactJS, NextJS, etc...) with Unity editor for WebGL games?
Thanks This was the answerer I was being stupid and had an error in the event that was being called and had my debug logs turned off in the console.
what for ?
Yes why not? The question is, in what capacity though?
Unity WebGL games are essentially static HTML-like content. Like an image. You don't need a NodeJS server to host such a thing
Blockchain wallet integration for a game
If you want to have a server that your game can make HTTP requests to, of course you can
it's just a normal web application
Right now I have to build and then deploy onto our server to test
I have no experience with that lol. Can I find that in the Unity docs?
You can also use https://www.colyseus.io/ for node .js
I tried it but didn't really care for it.
I mean there's pretty much infinite things you can use for a web app framework. That as a universe is as big or bigger than game development
Can I connect it to a reactJS server? So it's possible to connect to http://localhost:3000???
I'll read through the unity docs first
assuming you're hosting a server at that host/port number, absolutely
Isn't ReactJS more for making frontend GUIs? Node JS is for servers.
indeed React is a clientside frontend
Sorry guys coding isn't my day job. More of a hobby really. So I don't know if I'm describing what I'm trying to do correctly.
probably not lol
If you're just asking if Unity can make HTTP requests to a backend server, yes the answer is absolutely yes.
In the context of WebGL you might have to be familiar with web development things like CORS though to get it working properly
another possibility instead is ASPNET , you can use Swagger which is really nice to work with
keeping everything c#
I believe azure gives you a way to host an aspnet server free
We have a webGL slot machine game. Theres a UI (using blockfrost API, Lucid, MeshJS, React, etc...) that allows users to connect to cardano wallets (nami/eternl). They can then deposit our token into the game. Bet, Spin, etc... and then they can withdraw that token from the UI. Right now the only way I can test the wallet UI is to build and deploy the game on a server. I'm just trying to research some info if that's possible to test directly in the Unity editor.
I could just upload all the code lol
if you have an API you can work with you don't need to deploy to server no ? just make the HTTP requests
Ok I don't have any experience with that. i'll just read up on it.
just run the game in the Unity Editor. no?
have it point to a staging or local dev server
I can run the game in the editor but there's no functionality with the wallet in that enviroment
Yes this is more of what I'm looking for. How can I have it point to http://localhost:3000
There isn't a ton of API's or SDK's for the cardano blockchain. Dapps are still very new on the blockchain.
depends what "it" is
but... you just use that as your URL instead of whatever you're using now
You can also build the game and just either run it on a local web server or using Chrome's "load from directory" features.
and still - repointing your web requests to localhost
i mean if there's no browser
you won't be able to communicate with browser stuff
assuming you're talking about browser extensions etc
if it's not browser extensions then it's just a matter of pointing your game's API requests at the appropriate URL
So I can't test it within Unity's editor. I have to build and deploy.
can you show the API you're trying to use
I'm just trying to research some info if that's possible to test directly in the Unity editor.
you cannot test using their web based UIs and integrations. as you know those SDKs inject code into the page that other javascript apps, like your webgl game, can interact with. while you can recreate that context in unity, you cannot recreate the chrome extension environment that those wallets use as an approach to trust.
You surely can test within the Editor. Just make your webrequest point to the URL and send requests away
Ok. I was just curious. Maybe a more efficient way.
you can see if the wallets already have some kind of javascript development package that does not rely on a chrome extension to gather the user credentials. however, that seems unlikely
you can always write a way to gather the user credentials yourself for the purposes of testing, and then try to invoke their transaction apis directly
They don't. There is minimal stuff on Cardano
they would need to explicitly support that on their backend, or give you a token as part of their login process. this usually looks like OIDC
Again a lot of this stuff is beyond my scope. We paid someone to create the UI and wallet integration and then he ghosted us.
if i were you i would stub out this functionality in editor
i.e. stub out the jslib invocations you normally would do
and write a small mock for the wallet
because that way you can easily force error conditions anyway
i suspect moralis already does this
and may already support cardano
i don't know if any of it actually works
in this model, you don't need a backend server at all
the webgl unity game is a bunch of static assets that runs entirely on the client's computer. it can query balances, for example, directly through the wallet's SDK living on the page / your mock in the editor
@gusty hazel does this make sense?
however, engineering a p2p blackjack game that is cheatproof requires some very specialized knowledge
Clear as mud lol. I'm looking at Moralis. Doesn't look like its compatible with Cardano
incase the player clicks on a point on the grid,also i want to be able to click on the other side of the grid,not only be limited to the one with top right area
because there's stuff that @gusty hazel finds interesting, and there's stuff that @polar marten finds interesting
and they're different things
most blockchain based games do not / cannot interact with the blockchain using gameplay. traditional gambling games can, but the way they do is complex
right now, it sounds you are trying to make something valuable out of this blackjack unity project you received
is that true?
Utility for our token
Eventually we would like to build a full casino utilizing our token. One third of decentraland's daily users were from casinos. I'd like to see the same on Cardano. Help grow the blockchain, metaverses, partner projects, etc...
hmm
The problem we're running into is the majority of people that develop on "web3" are completely full of sh*t.
At least those we've interacted with so far on the Cardano blockchain. I can't speak on other blockchains.
well other than litigating something like that to death, what is something that would be helpful to know
All you guys have been helpful and I appreciate that. Right now I'm just going to dig into Unity docs and educate myself more on the editor and it's capabilities.
okay. this is the start of a long journey
lol I can only imagine at this point. thanks again!
they’ve got some good classes you can look at, if you want to learn “their c#” you can look at create with code, it worked good for me, but then again i learn at a inhuman rate
for sure even i’ve only barely scratched the surface and i’ve been at it for a good 4 or 5 months now
Hey there folks! I was thinking about it, and I may try using the new input system. Is there any major downsides to it that's worth knowing about?
I thought using the legacy system would be easier, but now it's looking like I would need around 8-10 functions in a script just to make the controls menu and I think the new system would simplify it a lot.
Whenever I try to schedule notifications with unity.mobile.notifications through Android, they're unreliable. They don't fire when they're scheduled to fire, and they don't repeat the way they should. It feels like they only fire when I close and reopen the app. Is this a known issue, am I missing something obvious?
only downside is the initial learning curve, it literally puts the old input system in it's place
I'll learn that then, I'm new to unity so it's better to learn it sooner
It just sucks because I spent all morning designing an input customizer for the old system
I'm new to a lot of unity, too. Is it possible to input a point and detect whether or not an object is located there?
2D or 3D?
2D.
Best case scenario if it's possible to get the object's name
There's a physics query for everything:
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapPoint.html
^It returns a Collider2D which belongs the object you hit
And you can access the name property of that collider. It is the name of the gameobject
It's generally bad to use object names for logic though. There's also "tags" and "layers" which you can use
Can someone help please?
I have never done 2D pathfinding but it seems the tutorial you linked already allowed the user to click on the grid. Still It seems your issue is that you have an array out of bounds. Maybe someone else can help more than I can.
yeah,my problem is that i am trying to make it so that can convert from Vector2 to int2 and vice versa + count as grid starting in center instead of in the bottom left
Are a lot of dictionaries ok to have?
Can someone suggest a guide to make a a chat app like discord / wlm 2012 with unity 2017.1.0
Why
sure why not
unity is better suited towards making games.
Aight just didn't know if they'd impact performance or be bad to have a lot of in some way
everything you use takes up memory
how you use it is important of course
there's nothing intrinsically bad about dictionaries but too much of anything is bad of course
you need to test/profile your game on your target hardware to determine if you've reached "too much" yet
I'm trying to have one object follow another do I have to have it in update?
LateUpdate is probably better
Aight
You could also consider using the PositionConstraint component
rather than writing the code yourself
Ok
I just realized it does need to update because the list of items I'm trying to have follow something changes during runtime
I’m saving money so I can’t get vs 2017/2015 licence
I doubt the free version is too expensive
Unless you're a company that does more than $100k/year in gross revenue, then you can get the Community edition for free
Is it possible to create an attribute that can execute code on a MonoBehaviour's Awake() message?
that better be sarcasm
you mean like this?
[MyThing] private void Awake()
No like,
[MyAttribute]
class MyClass : MonoBehaviour
{
}
I want the attribute to execute some code when the Awake happens.
what is the idea?
attributes can't execute code that way
nah not really not without being able to modify the engine which is what is responsible for invoking Awake
I don't understand why can't you just like Invoke an event or call the code directly lol
Yeah I thought that might be the case, basically I wanted to add a component with a supplied type based on if the application is the server or not. I didn't want to have that logic to every class that needs it
I can just make a method that the awake method calls though. I was just curious if something like that was possible
Thanks guys!
you can do
var targets = FindObjectsOfType<NeedsAnnotation>();
foreach (var target in targets) {
target.AddComponent<MyServerOnlyComponent>();
}
or even
var targets = FindObjectsOfType<MonoBehaviour>().OfType<INeedsServerExtension>();
foreach (var target in targets) {
target.AddComponent<MyServerOnlyComponent>();
}
and yes, you can use attributes too to achieve this
That would work if it was a one time call for all objects currently in the scene, but I wanted it to execute for a any object once it is spawned.
yeah i think you are best off with a ServerBootstrapComponent maybe.
is there an equivalent of Object.DontDestroyOnLoad, but for an entire scene?
do not know don't think so, but you could theoretically put everything into one empty gameObject and do it on that
alright, seems fine for my use case (pause menu and other global components)
you could also write a method that gets all root gameobjects in a scene and calls DontDestroyOnLoad on them
public static class SceneExtensions
{
public static void DontDestroyOnLoad(this Scene scene)
{
foreach (var go in scene.GetRootGameObjects())
{
GameObject.DontDestroyOnLoad(go);
}
}
}
usage: scene.DontDestroyOnLoad()
You probably want to unload that scene after calling it since it'll be empty
good point
I have decided to use Let'sBlend's option of putting my objects under a top component alongside a singleton to destroy it were it to be the case that I get to that scene again (even though it shouldn't)
public class DontDestroyInstance : MonoBehaviour
{
public static DontDestroyInstance Instance { get; private set; }
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
}
else
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
}
}
Why a singleton though?
so that it is ensured to only ever have one, as this will have things like the player's current state and such.
Yeah but your classes that have that state should be singletons in that case not the gameobject that contains them
true true
Here's my code: https://paste.ofcode.org/6duL8YUtE9eukuvPvG4eGL
Here's my scene/game view.
I'm trying to spawn primitive objects by right-clicking somewhere on the canvas by shooting rays, and wherever the ray connects to a collider, it should spawn a shape.
However, right now, nothing is spawning. No objects whatsoever.
Normally they appear as children of my "click manager" object (which this script is attached to).
when you say canvas, do you mean Canvas?
don't use scenes. then you don't need dontdestroyonload
use prefabs instead
put your whole menu hierarchy in your game scene
@steep prism
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
public static T Instance { get; private set; }
protected virtual void Awake()
{
if (Instance == null)
{
Instance = this as T;
DontDestroyOnLoad(this);
}
else
{
Destroy(this);
}
}
}
public class MySingleton : Singleton<MySingleton>
{
protected override void Awake()
{
base.Awake();
// additional awake logic here if needed
}
}
No, canvas is just the physical canvas you see on screen. the one i put a texture on.
Hello guys
i just built with XCode and it failed it without any Errors..
what do you mean spawn primitive objects?
shooting rays... what are you trying to do
draw on this board right?
i have a hard time telling if it's a 3d object or not
yes, and i'm trying to spawn 3D primitives (like the sphere, cube, cyllinder, capsule) on the canvas you see in my game view. only on the canvas too (i'm trying to make the ray only hit a particular layer)
@dreamy vapor the component on the drawing board should look something like
public class DrawingBoard : UIBehaviour, IPointerClickHandler {
public GameObject toSpawnOnClick;
protected override void Awake() {
// set up your scene for events in 3D
var physicsRaycaster = FindObjectOfType<PhysicsRaycaster>();
if (!physicsRaycaster) {
foreach (var camera in FindObjectsOfType<Camera>()) {
var raycaster = camera.AddComponent<PhysicsRaycaster>();
raycaster.eventCamera = camera;
}
}
var collider = this.GetCollider<Collider>();
if (!collider) {
var meshCollider = AddComponent<MeshCollider>();
meshCollider.convex = true;
}
}
protected override void OnPointerClick(PointerEventData pointerEventData) {
var worldPosition = pointerEventData.pointerCurrentRaycast.worldPosition;
var newPrimitive = Instantiate(toSpawnOnClick);
toSpawnOnClick.transform.position = worldPosition;
}
}
don't use the word canvas
to describe the drawing board
you don't need to do raycasts
or clicking or Input.mousePosition or any of that nonsense
EventSystem which you already have because you have UGUI elements gives you all that already
these are just the methods they taught us in my class. i think they're expecting us to use methods like these
i meant the ones i mentioned, btw
like raycasting
i think you'll figure it out
this is wrong. it should actually be where T : Singleton<T>
@steep prism you shouldn't use an abstract base singleton whatever
But is it possible to do it with raycasting though? That's where I got stuck. 
well i think that's the core of the homework so you gotta figure it out
i can't really tell what's going on. i wrote the way i would do it
that's fair. thank you.
hey, so i have a problem with i cannot seem to solve. basically i have a floppy bird type of game and i have the enemy spawning in and trying to reach pipes, but i also wanted it to avoid those pipes. but when the enemys ray is on top of the pipe it tries to move towards the bird and go up/down at the same time with makes it look like its having a stroke. i tried to solve that with the isbirdaccesable method you can see in my code. but right now it just always returns true. i also tried this code, with also didnt work:
{
RaycastHit2D hit = Physics2D.Linecast(hitinfo.point, bird.position, layerMask);
return hit.collider == null || hit.collider.name == "bottom pipe" || hit.collider.name == "top pipe";
}```
my code: https://hastebin.com/share/wowifukaco.java
i would be very thankful for any help
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hey! I asked this in #💥┃post-processing , but I just wanted to see if anyone in here also has any idea about this...
Can I lerp a chromatic aberration effect during runtime? Like maybe through an animation or something?
Sure why not? The weight of the volume is a property you can modify like any other
Exactly, thats what I thought. But when changing the variable, it doesnt record during animations, and I can't change the variable itself with MathF.lerp
Why not, to the latter part
I'm not sure, I've tried it and it doesn't work. I could send code to check if there might be an issue.
Probably a code issue yes
Here's a basic version:
{
if (Input.GetKeyDown(KeyCode.O))
{
AbIntensity(2f);
}
}
public void AbIntensity(float time)
{
Mathf.Lerp(_chromaticAb.intensity.value, 1f, time);
}```
Pressing "O" doesn't do anything in this instance.
You're ignoring the result of the Lerp call
Also using 2 as the Lerp parameter is pointless
are there any huge differences between interfaces and abstract methods? (unity wise). only thing i can think of is with doing e.g IDamageable and have anything damageable implement that, no matter how far related they are, but using abstract methods are more tightly coupled to whatever class inherits that abstract class that has the abstract method and is usually closer related
Abstract classes are actually classes. They can have fields
And you can only actually inherit from one class
You can implement as many interfaces as you want
Basically notice how you never wrote _chromaticAb.intensity.value = something anywhere here, so of course it won't change
Oh! So what should I do to clarify? Something like _chromaticAb.intensity.value = ??? after the Mathf?
C# is a single-inheritance language, so yes there will be differences. You can only have one base abstract class. With interfaces, you can tack on a "kind of" approach to defining what a class can and cannot do. They're similar in function, but as PraetorBlue just said, an abstract class actually is a class.
Should I be putting this in Update do you think?
I feel like that may be a little resource instensive
You want it to change over time right? You will need to be running some code in Update or using a coroutine for that
You can think of abstract classes and interfaces as a top-down / bottom-up approach to describing an object. Abstract classes make for a common underlying framework for whatever inherits from it while interfaces mark that a class can suffice to squeeze through a certain-shaped hole. Interfaces declare that a class is suitable for a certain behaviour, such as being "IDamageable", etc.
I see. Alright, I'll try it with coroutine.
You should also look into DOTween
It makes things like this quite easy
Oh, alright. Here I'll look into it right now.
so interfaces are more open and less restricted to what logic they can have?
Interfaces never provide an implementation. When you add an interface to a class definition, you're declaring that the class will provide one.
You're always "tacking on" behaviour with an interface in the opposite direction that an abstract base class would be "building it up".
@stuck forum For a concrete example, let's say that you have an enemy that the player can attack as well as a special breakable wall.
The enemy, being an entity of sorts might inherit from some base class that has a health pool, but the wall isn't similar enough to an enemy to inherit also.
To spread the behaviour of being able to take damage around, you can have both the base enemy and your wall implement an IDamageable interface which handles what happens when the player attacks. In the case of the enemy, it might subtract health. In the case of the wall, it might trigger some other behaviour that never uses a health pool so to speak.
The player attack could target any IDamageable in this case and both objects would receive the method invocation. You can keep your classes that define enemy behaviours totally separate from any description of what can take damage this way.
Hello, I am trying to integrate the multiplayer system with unity. I came across Netcode but it's only about Unity. I want to run the multiplayer infrastructure on Steam. What can I do for it?
This isn't a complete answer, but I believe you'll want to look into this: https://partner.steamgames.com/doc/features/multiplayer
@earnest epoch i see, that does make a lot of sense
i guess i was just over thinking a bit since i saw some c# tutorials about interfaces and abstract methods, but usually in Unity you do GetComponent for interfaces so it's easier done that way, but standard c# doesn't have that so i just struggled to see the use case outside of unity
Ugh, that's a confusing way to look at it, but you're somewhat on the right track.
does anyone know how to solve this one? i suppose for anyone with expirience it will be very easy
Components provide behaviour to game objects as interfaces provide definition to classes, but Components are implementations and interfaces are not. An interface is a contract that states that any class that implements it will define a body for whatever methods are declared by the interface.
Again, C# is a single-inheritance language. Multiple-inheritance like LUA allow exactly what you're thinking of, but there are pitfalls for OO that come with developing that way.
i do know what interfaces do, i guess i just, for some reason, see a blurred line between abstract methods and interfaces, even tho it shouldn't be a blur
base class: is fundamentally X. Interfaced: provides function to do X
ah
On this note, all abstract means is that the base class makes no sense by itself and doesn't really affect inheritance.
abstract classes main use case is for classes that will share a lot of similar logic. Interfaces are just a blueprint that forces you to override those methods.
Maybe you have a hard time wrapping your head around their purpose because Interfaces solve a problem that you only really come into contact with if you work on projects that involve multiple people and changing specifications over time. They allow you to define a minimal set of specifications that need to stay the same for a system to remain operable while everything else that’s not exposed by the interface can change. You can achieve such decoupling without having interfaces as a language feature but in OOP having them as a language feature is very convenient.
I see that does make sense.. hmm
I'll definitely read on about abstract/interfaces since i rarely use them and it would be great to know more about them
Again to be clear, abstract really only marks a class as being uninstantiable. You can inherit from base classes that are not marked as abstract.
What's the best way of linking one variable to another that takes up the least amount of resources? Like, for example, if I wanted a to be equal to b at all times, what would be the most efficient way of doing it?
(I ask because I feel like a = b in Update() might be a little too resource-intensive)
it's not particularly intensive, but probably unnecessary - why can't you just use b in place of a to begin with?
a is the intensity value of my chromatic aberration postprocessing effect and it can't be edited directly through animations, my work-around is to have b be a public float that I can change during anims and then just set the chromaticaberration.intensity.value(or "a") to b during update to simulate the process of animating it directly.
this would all be chill if i could just directly animate post processing values from the inspector but for some reason i can't
GameObject unGo = new GameObject();
unGo.name = "newFou";
System.Type fouClass = Type.GetType("Fou");
Piece fou = (Piece)unGo.AddComponent(fouClass);
fou.dxDalles = dxDalles;
Debug.Log(fou);
Hello, just to be sure, is this a bad way to use AddComponent? I used a GetType of a string to add it. I know using a string with AddComponent is obsolete, but this one works when I use the type from GetType("My string
AddComponent<MyComponent>();
Yeah but let's say I can't just used that because I want to add dynamically scripts wich arnt gonna be the same.
Piece here is a parent of Fou, and many more
huhhhh
oh you want to add component using a string ?
Well that's the most legit way i found
im not sure if it's still considered legit tho
what's the intended usecase
That's getting into reflection, which is probably a terrible idea as we're now reading assembly and asking the machine to do machine things in human language.
Right now it's mostly for fun, but I found that it could indeed work for adding Monobehavior script in with a ScritpableObject
It works but isn't really the best way to do it lol
I call this a win lol
If it's for fun, I encourage you to look into the System.Reflection namespace, but know that 99% of the time this is not what you want.
My curiousness will lead to my fall lol
It's absolutely worth learning how to read the assembly from inside the assembly!
use a prefab
🥺🥺🥺
I've been looking around for over half an hour and I'm probably just blind and terrible at google, but I can't find anything about how to make a controls menu using the new input system. I have a vector2 and a button input, and I want to figure out how to change them in my script, and I can figure out the rest for making the menu from there. Does anyone know how to do this or have a link to a docs page that explains it?
Yup, I'm working on it there now, somehow I didn't see that channel
im using the particle system and the particles are following the player without me doing anything. anyone know why thats happening?
What is it parented to?
In the video, you have a search term blocking the hierarchy view.
Small detail, but, if you do go down that path, just consider the gettype might fail or return null. So you might want to put something defensive in there. If it is being open ended and all.
Creative solution though imo
the torch
is a component in the torch
and the torch is in a chunk game object
dw i figured it out 😛
i think there's prefabs for this and examples in the input system package
what is the ideai think it's simpler to just have a big switch statement for the strings
whats the correct way to do this? (new input system)
void Start()
{
input = new IInput();
input.Main.Enable();
input.Main.LeftGrab.performed += Grab(1); //these errors
input.Main.RightGrab.performed += Grab(2); //
}
void Grab(int side)
{
// 1 = left, 2 = right
}
input.Main.LeftGrab.performed += _ => Grab(1);
The problem here is that .performed is looking for a specific signature which is not (int). You can probably get around this using a lambda like so, though I can go on to explain why it's not ideal. input.Main.LeftGrab.performed += _ => Grab(1); //these errors
The problem being that you can't unsubscribe a lambda.
The main problem is that you passed in void to the += operator instead of what the event actually needs which is a delegate.
@novel raven Ideally, you would point that to a method to handle the performed call and then contain the Grab(2) part. For example:
public void DoLeftGrab(InputAction.CallbackContext context) {
Grab(1);
}
You could then unsubscribe with input.Main.LeftGrab.performed -= DoLeftGrab; when cleaning up your class.
The subscription / unsubscription can go in either Awake and OnDestory, or you could set them up in OnEnable / OnDisable. The point is, every += should have an equivalent -= to clear it when cleaning up your class.
would the subscription persist across sceneloads? because that would be the only reason i would need to unsubscribe
since you're creating this IInput object here, it will only live as long as your script does
If the class doesn't unload, it should be fine.
So I've been getting mixed answers. Are basic floating point operations deterministic or not?
Like if I do 1.32894828 * 100, will that always be the same outcome regardless of hardware vendor?
It can vary from CPU to CPU
Different CPUs do floating point math at different levels of precision.
The guys in the C# discord are claiming it's completely deterministic regardless of hardware
and cited a IEEE standard
Are they claiming floating point ops in general, or this particular operation?
1.32894828 * 100
in general
whoever "they" are, they're wrong
what he isn't taking into account with his answer is that not all processors support the same formats for the calculations
apparently the tanner guy is also the numerics lead
also correct about the sin/cosine stuff
Bro I cant figure out whats wrong with this god damn string
So like, if it's an AMD or Intel CPU, it should be deterministic?
I don't plan on writing code for a 1970s mainframe anytime soon
it can vary across different models even within the same brand
it should be deterministic on the same model
right
my brain hurts and theres about to be a new hole in my wall
you might have anger issues
best to work through that with a professional
Praetor
How tf am I supposed to not be angry, when this string, is refusing to get set
this fucking string has issues
Seems more likely you have a misunderstanding about how C# or Unity works
I am doing it exactly how Im supposed to
if code irritates you like this find another activity
Don't make jokes in the unity discord, noted.
maybe your parent canceled your wow account
wow
If you don't have code or a question, this convo can be avoided
lmao
This error message isn't telling me where the out of range index is
Its only when the DropItem method is run so it has to do with it, but no where in there do I mess with any indexs, I check if a list contains an item and remove items from 2 lists but thats it, the object cant be out of the index or it wouldn't have been added and it would throw the error when the pickupobject is run
MenuButton.cs line 47
(though that line might pint to the } at the end of the method
its in a place where you try to access a particular item (hence the get_item call in the trace)
but that for loop has been working for a while and I haven't touched it
Thats run in onvalidate
the error is from a button click handler
wtf is wrong with the button damn it
nothing's wrong with the button but the code it's invoking is encountering an error
oh shit I was looking at the wrong script
Hey, so i downloaded unity just now (used it before dont worry, and know some stuff on c# and cpp XD)
But i was wondering how to make a shader, so i downloaded a URP and well, you can see what i mean. I use a default shader from that render pipelineand it goes coconut texture style 💀💀
please dm if you know what did i do wrong (cant check this server 24/7)
u can use shader graph for making shaders
If you're concerned about everything being pink, you may have to convert the shaders in your scene to be appropriate for the pipeline you have set. See this option at the bottom of the Edit menu:
You can also ask in #archived-shaders, some people still write their own ones without Shader Graph.
Physics.OverlapSphere in editortime doesn't filter the layer
does it happen to you too?
Never. This sounds like a semantics issue.
what you mean with semantic issue?
I don't think OverlapSphere is failing you, rather you're probably feeding it something bad or using it wrong. (no offense intended).
Show your code, last guy that had problems with this put the layermask in the distance variable.
ah ah
anyway I found the problem. my code was for replicate the triggerenter and triggerexit in editortime and i miss that one gameobject calling the overlapshpere was on ignoretrigger layer that is correct for my purpose on play, but with overlap it doesn't care about the self layer (correctly). thanks for confirming that overlapSphere was right
Glad to hear that you figured it out! Generally, the physics methods in Unity do very simple jobs, so there are no surviving cases where they don't produce a reasonable result.
yesterday i got stucked on 2 unity's "bug" (in my opinion bad choices) so i gave the guilt to unity's method too fast xd
the bugs are:
- collider with radius = 0 still trigger if inside other collider
OnEnablein a class with[ExecuteAlways]gets called twice at start playmode
- I wouldn't profess to expect any specific result from a collider with radius 0. In real world terms, that makes no sense.
- Is this possibly because the editor and the game are calling OnEnable separately after launch? Each is running in their own assembly.
- Having a collider with 0 radius is still a point for Unity, even if "infinite", but as you have a collider, something is there
- OnEnable will get called everytime if you set so first from editor and second from playmode. Hence the docs saying "Makes instances of a script always execute, both as part of Play Mode and when editing."
I would never think to use a collider with radius 0. Is this really planned behaviour?
My intuition suggests this conflicts with Collider volumes not being convex.
I think it makes sense as a an object in unity environment is not null if you have it as a component. Does it make sense to set so? No, but you are able to use any float you like, including 0
That counts into that. You cant just have an empty collider "mesh". Why would someone add a collider with radius 0 might be the better question then why does it work 😄
Precisely my pause. :/
Is there a way to access code from a package that has an asmdef file without creating another asmdef file?
?
Hey guys, I've been programming a custom player controller without a rigidbody and a character controller(basically just raycasts and capsule casts) with some vector math to make wall slide, check if on ground, apply gravity etc. Needless to say this is horribly painful to think about ahah but im doing it as a learning experience. But it got me thinking, is this normally done ? Or do real games normally use rigidbody or character controller,if they do which ones of this two is most used ? I would assume rigidbody since it seems less restrictive but I would like some examples of games and what they use
if you guys dont mind
I believe Unity should detect it by default if you regenerate project files, if you do have your own asmdefs already though you may need to add it as a dependency yourself
I have base class A and B as class that inherits.
How can i execute only variable = 1 in base class, then for instance variable=2 in inherited class and then invoke back in base class?
public void Foo(){
variable = 1;
Event?.Invoke();
}
Dont know to explain it differently
I thought about subscribing function in inherited class as first function in event but dont like that method because seems clunky and prone to error.
Thought about having aditional protected event that calls internal functions and triggers, before public event but that doubles event count.
Or i have to override function in inherited class but i dont like that approach as i have to change something in multiple places if i change something in base class
Hello guys, in Mac, anyone got an issue like that ? the app started with an black screen ?
#📱┃mobile might be better for this. Can you post your error there?
Don't assign it anywhere. Make it a virtual property instead of a field
!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.
public virtual int Example => 1;
public override int Example => 2;```
@fiery saddle
Pleae help I get a null reference when trying to use this and I cant figure out why?
public Vector2 NearestCheckpoint(Vector2 position)
{
float nearestDistance = Vector2.Distance(position, Spawn.position);
Vector2 nearestCheckpoint = Spawn.position;
foreach (Checkpoint checkpoint in _checkpoints)
{
float distance = Vector2.Distance(checkpoint.transform.position, position);
if (distance < nearestDistance)
{
nearestDistance = distance;
nearestCheckpoint = checkpoint.transform.position;
}
}
return nearestCheckpoint;
}
Where do you get the null reference?
Its more complex with function calls, that was example :/
You mean base.YourFunction(); ?
NullReferenceException: Object reference not set to an instance of an object
GameManager.NearestCheckpoint (UnityEngine.Vector2 position) (at Assets/Scripts/GameManager.cs:41)
GameManager.Update () (at Assets/Scripts/GameManager.cs:64)
void Update()
{
if (Lifes < 0)
{
//Game Over
}
Debug.Log(NearestCheckpoint(Spawn.position));
}
What line is the error exactly? These are 9 lines
float distance = Vector2.Distance(checkpoint.transform.position, position);
Give the real code if you want a real answer
Just from this snippet, it can only be position or checkpoint being null
Fixed it
before:
private List<Checkpoint> _checkpoints;
now:
private List<Checkpoint> _checkpoints = new List<Checkpoint>();
I would also recommend using readonly:
private readonly List<Checkpoint> _checkpoints = new List<Checkpoint>();
It doesn't make the list itself read-only, but just the _checkpoints variable. It guarantees that it can never accidentally be set to null or some other list instance.
I want to multiply a direction to get a position from direction
Vector3 ramDirection = (_sm.target.position - _sm.transform.position).normalized;
_ramPosition = ramDirection * _sm.ramAttackDistance;
_ramPosition.y = _sm.transform.position.y;
I use this code but it gives a position far from the direction
anyone knows why?
Multiplying a direction by a scalar as you do in your second line of code does not result in a position vector. It results in a scaled direction vector
I would suggest adding a debug object to your positions, start, direction normalized result and the final multiplied position.
I don't understand what you mean by "far from the direction". A direction doesn't have a position, it's always from the (0, 0, 0) world center.
hmm I want to get a position in the direction how can I do that?
Add it to the position of the object it's relative to
Actually all of this code can be simplified to one line
ohh okay
Vector3 ramPos = Vector3.MoveTowards(sm.transform.position, sm.target.position, ramAttackDistance);```
Unless you want to be able to overshoot
ohh I will try it, thanks man!
Hi have problems changing a gameobject layer
What are your problems
I have this code inside coroutine:
[...]
yield return new WaitForSeconds(TIME);
gameObject.layer = LayerMask.NameToLayer(LAYER_NAME);
[...]
yield return new WaitForSeconds(duration);
gameObject.layer = LayerMask.NameToLayer(LAYER_NAME_IGNORE);
[...]
the gameobject change it's layer the first time
but he doesn't swicht back
Ok so it sounds like you actually have a problem with coroutines not with changing layers
the code is executed until the end
How do you know
debug.logs
I do I prevent GameManager based scripting from becoming spaghetti code?
Either running this code multiple times (starting coroutine in Update perhaps?) Or some other code
Are you running ths coroutine more than once at some point?
"Ignore Raycast" is the correct name for the default unity layer Ignore Raycast?
Like a coroutine still running while you start a new one?
What is "GameManager based scripting"?
I think he means singleton pattern for global manager scripts
Basically every object in the scene talks to a game manager
nope, to be sure I have a control on startcoroutine:
if (_coroutine != null)
{
StopCoroutine(_coroutine);
[...]
}
_coroutine = StartCoroutine(PlayCO());
and at end of coroutine i set the variable _coroutine to null
To do what
So not the easy fixes here, damn 😉 Are you sure your second layer exists?
the second layer is Ignore Raycast
show your console window with these debug.logs etc
To handle the level’s state
in what way? What kind of state is it handling
can you show examples
Like if the level is completed or if the player died and we need to respawn
I could imagine that NameToLayer fails and therefore its not changing
Basically the answer is you should keep in mind the "Single Responsibility Principle". If GameManager is doing too many different unrelated things, it should be split up into multiple scripts
try adding a public LayerMask dropdown and select from there. See if that works for testing
#archived-networking Might be better maybe? not sure
private IEnumerator TestCO()
{
Debug.Log($"Layers: {LayerMask.NameToLayer(LightManager.LAYER_NAME)}, {LayerMask.NameToLayer(LightManager.LAYER_NAME_IGNORE)}");
Debug.Log($"TestCO. pre change 1 layer={gameObject.layer}", gameObject);
gameObject.layer = LayerMask.NameToLayer(LightManager.LAYER_NAME);
Debug.Log($"TestCO. post change 1 layer={gameObject.layer}", gameObject);
yield return new WaitForSeconds(duration);
Debug.Log($"TestCO. pre change 2 layer={gameObject.layer}", gameObject);
gameObject.layer = LayerMask.NameToLayer(LightManager.LAYER_NAME_IGNORE);
Debug.Log($"TestCO. post change 2 layer={gameObject.layer}", gameObject);
}
It seems correct reading logs, but in the inspector top left i see the layer 17 on the gameobject
ok so it's working perfectly fine
if the layer is something different later on, it's because some other code is changing it, or you're looking at the wrong object.
What's the correct way to write #if UNITY_EDITOR #endif and then have an if for it being a build instead of editor?
#if UNITY_EDITOR #endif is exactly have an if for it being a build instead of editor
#if !UNITY_EDITOR
Checks if the preprocessor does not exist basically
@thin aurora oh does that work, ok thanks
#if UNITY_EDITOR
// editor stuff
#else
// non editor stuff
#endif```
i tried #else but it just greys it out and didn't know if it works or not
Yes it greys out in the editor because it exists 🙃
But it will work in a build application
fair, thanks
If you need to validate the code syntax you can always change the block to be in reverse and the other part will grey out, allowing intellisense to work on it.
that means it's working
whats the best way to do an inverse kinematics animation approach
good job! I hate myself, I was changing the layer on the parent class
i have an enemy that will violently hunt down the player, and the idea is that he will use his full body to mobilize himself more