#archived-code-general
1 messages Β· Page 327 of 1
Though this will be lil bit complex that you need to consider wrapping
I just wanna clamp my x and y
as youve been told, euler angles
so what does that mean exactly? character.localEulerAngles = Math.Clamp?
I have some pieces of code about rotation here https://github.com/cathei/RotationMath/blob/main/Packages/com.cathei.rotationmath/Runtime/RotationMath.cs
You can take a look at Yaw, Pitch and Clamp
Yes it is, angles may have range you donβt expect when it comes to clamping. 359 can be 0 at next frame. Then clamping works differently.
I'm trying to clamp the vertical axis of the player camera
not according to this ' Then you grab the euler angle, clamp it between desired values, Set it back onto the original Quaternion'
This does not work ```
public Quaternion ClampXAxis(Quaternion quaternion, float minimum, float maximum)
{
Vector3 euler = quaternion.eulerAngles;
euler.x = Mathf.Clamp(euler.x, minimum, maximum);
quaternion.eulerAngles = euler;
return quaternion;
}
public Quaternion ClampYAxis(Quaternion quaternion, float minimum, float maximum)
{
Vector3 euler = quaternion.eulerAngles;
euler.y = Mathf.Clamp(euler.x, minimum, maximum);
quaternion.eulerAngles = euler;
return quaternion;
}
So what do I do? Because that didn't work
Vector3 rotation
Start
rotation = transform.eulerAngles;
Update
// change value of rotation
// clamp properties of rotation
transform.rotation = Quaternion.Euler(rotation)
so you are only working with the rotation field in your code
@rigid island You couldn't make a vid on this could you, we have to explain it so many times
could be an interesting topic, there is good ones. I try not to cover the basic stuff, don't want to give wrong info out.
There is def a wild confusion between quaternions and eulers, something to show off the differences would be neat to do..
ya! we need more #1179447338188673034
Ok fen when can I expect that blog. Seen you solving plenty of problems here.
I'm trying to send data to google forms. It works but instead of one line of data, I'm getting four lines. As such, it counts one response as four. I'm wondering why that is. Here's the data I'm trying to send:
Here's the code:
public class SaveData : MonoBehaviour
{
private Slider slider;
private string currentQuestionData;
private string activeQuestion;
private Dictionary<string, float> saveDataDictionary;
private string url =
"HiddenFor Reasons....";
// Start is called before the first frame update
void Start()
{
SliderTicks.OnSliderValueChanged += GetSliderValue;
saveDataDictionary = new Dictionary<string, float>();
}
private void GetSliderValue(Slider slider)
{
activeQuestion = QuestionManager.Instance.GetActiveQuestion();
//Debug.Log($"Slider value for question {activeQuestion} is ::{slider.value}");
SaveFormData(activeQuestion, slider.value);
}
private void SaveFormData(string currentQuestion, float sliderValue)
{
saveDataDictionary[currentQuestion] = sliderValue;
}
// Update is called once per frame
void Update()
{
}
public void PrepareUserData()
{
StringBuilder result = new StringBuilder();
string id = "ID:007::";
result.Append(id);
foreach (KeyValuePair<string, float> pair in saveDataDictionary)
{
result.Append($"Key:{pair.Key}---Value:{pair.Value}::");
}
SendUserData(result.ToString());
}
private void SendUserData(string result)
{
Debug.Log(result);
StartCoroutine(Post(result));
}
IEnumerator Post(string data)
{
WWWForm form = new WWWForm();
form.AddField("entry.hidden", data);
UnityWebRequest www = UnityWebRequest.Post(url, form);
yield return www.SendWebRequest();
}
}
Here's what I see on Google Forms
obviously you are getting a new line every time you call the api, the timestamp tells you that
yes but why is that happening. As you see from the code, I'm only calling it once.
because Google is accumulating your calls
you are writing to the form, each write is a new line
It isn't. I'm simply passing a string.
it looks fine the second time you did it
and the screenshot you posted shows exactly one log item
from 15:04
perhaps it printed multiple items when you tried it at 15:01
do you not understand what this is telling you?
your code could be running it multiple times, but only under certain conditions
I do. But you're saying it's writing multiple times. Show me where I am calling write function multiple times?
you'd need an example where there's one item in the log and many items in the form
so far, you do not have such an example
This might be true.
Question. How would you go about implementing animations like these.
Where the target dynamically lerps from one position to another?
(5 sec clip) https://youtube.com/clip/UgkxCx13QFQ-3W8pffAtTSM06tJUMHHTBVCf?si=fEGCP0RwVMkudKnb
5 seconds Β· Clipped by SBroproductions Β· Original video "WITH THE HEROES AT MY SIDE, ONE CARD IS ALL I'LL NEED!" by MBT Yu-Gi-Oh!
Yes but what makes you say that google is accumulating my calls. And if that's the case, how do I fix it?
the time stamps tell me that, how to fix, no idea
maybe splines ? patterns
how do you know its dynamic
Seems to stretch from initial position to the final position.
run your code again, now. Bet you get another entry
yeah but likely only initial and end position change, the path is probably the same flipping motion
the confusion is that four entries appeared all at once
i think everyone here knows that hitting the API again will create another response
Okay I think I know why this is happening. https://discussions.unity.com/t/need-help-on-a-native-collection-has-not-been-disposed-resulting-in-a-memory-leak/245693
probably because he ran 4 time in quick succession withour checking inbetween
Webrequest needs to be in a constructor.
Nope.
you mean you need to dispose it?
Yup.
note that this isn't going to cause Unity to submit the request multiple times
also, that's not what you're using
this is talking about the obsolete WWW class
That is fair. In that cause I guess the XZ positions of all the points are being distorted, but the Y is the same?
Seems to hang at the top of the arc too.
(it just causes a memory leak, apparently)
using (UnityWebRequest www = UnityWebRequest.Post(url, form))
{
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error: " + www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
This fixed the issue.
i don't think it did anything
you should verify this by testing it again with the original code
It is the correct thing to do, mind you
I just don't think it caused multiple requests.
This error is output when a host a client tries to connect to a host. The client receives data fine but cannot send data nor perform any actions.
Trying to send ClientConnectedMessage to client 0 which is not in a connected state.
Reply pings would be much appreciated βΌοΈ
the card simply follows a spline path or does an animation in between the two points to flip it
watch the video at .2x speed if it helps
its just very well done to not look as simple, but it really is simple
Ya half of game dev is just lying to the viewer π
I'll mess around with splines then. How would you get that slow down at the peak?
Okay so I think you're right. What's happening is that when I recompile, the first time I only get one row of data (which should be the case). However, the second time, I get more. using keyword didn't make a difference.
I would assume playing around the rate of speed on the spline, possibly using animation curve to do so
No. I have no idea what that is.
also, what is "the second time"?
the second time you entered play mode?
Yes.
AnimCurves might be the best inspector element in Unity btw. They're so nice.
go to the Editor section of your Preferences and look for "Enter Play Mode Settings"
They are hidden gems indeed
the graph could be nicer though like the adobe ones
I see this in Unity 6. It's a set of checkboxes in older versions.
I ran once, clicked "finish" which triggers the script pasted above. Then I quit the playmode and entered the playmode again.
Oh 100%, but just being able to take some 0-1 range and remap it however you want is so incredibly powerful.
adobe's? pah
give me Blender's graph editor
haven't tried that one . Photoshop and Lightroom are basically my goto for 20 years
gonna try it, Hmm its open source, if I knew anything of c++ I'd try to steal the code for it
blender lets you manipulate your keyframes much like you can manipulate objects in 3D space
you can move and scale them around various origin points
if it's Blender it's probably python
you can even rotate them, if you so desire
I thought it had both ?
Blender is mostly C++ with Python for extensions
looks similiar to the ones in the animation window
graph stuff is an extension iirc
you can define new graph node types in Python, but you can't really make them do anything
I was just looking at this a day or two ago. It's understandable given the...performance characteristics at play
Okay. So the issue was that I had added listeners to the finish button twice. So the method was called twice. I cleaned up the code and now I don't see this issue anymore. But I still don't get why I was getting 4 or maybe 5 responses. Well that's not happening anymore so I'm glad. Thanks for your help, @heady iris @knotty sun
probably a double-click
@rigid island Considering I need to path the change based on the start and end target, do you think it would make sense to define the shape of the spline from a 0-1 range across all 3 axes, and then scale it along the vector between the start and end point?
@dawn nebula if you're looking to do the same thing , I would lerp the start and end pos dynamic, the "mid section" is the same flip animation/spline anim
Heyo, I just started to do some research about NavMeshComponents and I bumped into https://github.com/Unity-Technologies/NavMeshComponents/tree/master/Documentation . Is this still relevant?
these are old
they are part of the AI package now
cheers
Hi! I've been working on a state system, and I've hit a bump in the road. My idea was to store the states in a dictionary to reduce the amount of variables in the code. However, I'm now facing a challenge - I'd like to allow for easy drag-and-drop functionality for state scripts into an array within the Unity editor. Any suggestions on how to do it?
custom editor
There's examples online on how to serialize dictionairies to the inspector using custom editors. Odin Inspector has a sample on their website, and I think NaughtyAttributes also has one (unsure).
Can it enable dragging one interface object into a list in the Unity inspector? I use both an interface object and a key for each state
of what I've read it doesn't seem to be possible without a gameobject but asking in here anyways as I might have missed something
I don't know what you mean by "interface object"
Do you mean a MonoBehaviour that also implements an interface?
if so, you could consider https://github.com/Thundernerd/Unity3D-SerializableInterface
So is there a way for me to check for all vertices in a mesh within range of an arbitrary point that is faster than cycling through each and every vertex and measuring distance?
@rigid island Unity's spline package seems to cause a stackoverflow every time I click a knot, breaking the editor.
π
Yep every single time.
Wow
what version? been working fine for me 2022
Spline 2.6.1
Unity version 2022.3.27f1
you tried restart before?
reproduce that in an empty project and submit a bug report
what versions you got?
I'll try it
Just an implementation of an interface fx IPlayerState then IdleState : IPlayerState
2022.3.16f1 & 2.5.2
So this class is not a Unity object?
Hmm. Maybe I can try 2.5.2. Is there a way to get past versions from the package manager?
yup, just a raw interface that I want to use with Unity
used to be
idk how to do it now, unless you use manifest i suppose
just change the json?
I believe that https://github.com/Thundernerd/Unity3D-SerializableInterface works for non-unity-objects as well
I will give it a try seems promising
yeah, see
afaik
using UnityEngine;
public class MyPoco : IMyInterface
{
/// <inheritdoc />
public void Greet()
{
Debug.Log("Hello, World! I'm MyPoco");
}
}
this example
So I can drop raw scripts in with this plugin?
well, you can serialize instances of classes with it
If I understand this lane writes you can: "Classes (custom classes that implement said interface)"
You can already do this if you don't need to allow for polymorphism
So if I have implemented a class with this plugin the script will be an option to put in the inspector
[System.Serializable]
public class Stuff {
public int foo;
public char bar;
}
you can serialize a Stuff field just fine
if you put a SerializableInterface<ISomething> myObject; field into your component's class, you'll be able to serialize...
- A reference to a scene object
- A reference to an asset
- An instance of a class
I use something more like https://github.com/vertxxyz/Vertx.SerializeReferenceDropdown with abstract classes and [SerializeReference]
What I try to do is to have a state manager and a base state(which is a raw interface) I don't want to create a class to wrap the interface. Then my plan is to do a state system with a dictionary that contains the states, so I easily can swap state implementations and change references to states
I'm having an issue with my Assembly Definition for code in an Editor folder for a custom package I have created. Everything else works for my runtime assembly definition. But the editorone doesn't let me access anything in the UnityEditor assembly. Am I doing something wrong or is this a bug?
You won't be able to access it except from code in another assembly definition with an appropriate reference set up
That shouldn't affect me calling stuff from UnityEditor should it?
Becasue I have the other assembly definitions set up and they have the correct depencencies.
Or wait I think I misread. Show the inspector for the asmdef?
You excluded the editor platform
Splines.Runtime has the SplineEventSelectorData class in it and it should work
π€
let me try changing that
I think you did at least that tooltip is blocking things hehe
You probably want the opposite
You want ONLY Editor
yea, scroll down
oh wait, you don't toggle between "exclude" and "include"
you just check everything except Editor
(but there is a "select all" button at the bottom!)
OH ok hold on let me see if that works for me.
Yep, broken on a completely empty project.
Brutal.
!bug report time!
πͺ² To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
π If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click βReport a problem on this pageβ!
π‘If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
Oh ok that fixed it
Thanks for the assist π
ah! that's what does it
Also thinks
Seems 2.6.1 came out literally yesterday. Unlucky for me π
yeah unlucky for you, but lucky for everyone else you found a bug in that version so it can (hopefully) be fixed quickly lol
Alright packaged and sent, now to rewind until it... doesn't do that.
Happens on 2.6.0 too >_>
And that's from April
...crashed on 2.5.2?
What... is going on.
This is an empty 3D URP template project.
time for unity 6
public void GenerateGrid(CellInfoDatabase database)
{
for (int y = 0; y < gridSize.y; y++)
{
for (int x = 0; x < gridSize.x; x++)
{
GameObject tile = GameObject.CreatePrimitive(PrimitiveType.Plane);
tile.GetComponent<MeshFilter>().mesh = meshRef;
tile.GetComponent<MeshCollider>().sharedMesh = meshRef;
tile.name = $"Hex_{x}_{y}";
tile.transform.position = GetPositionForHexFromCoordinte(new Vector2Int(x, y));
tile.transform.SetParent(parent, true);
TileInfo cellInfo = new TileInfo();
cellInfo.LocalName = tile.name;
cellInfo.CurrentColor = Color.green;
cellInfo.ID = new Vector2Int(x, y);
database.CellInfos.Add(new Vector2Int(x,y), cellInfo);
}
}
}
public Vector3 GetPositionForHexFromCoordinte(Vector2Int coordinate)
{
int column = coordinate.x;
int row = coordinate.y;
float width;
float height;
float xPos;
float yPos;
bool shouldOffset;
float horizontalDistance;
float verticalDistance;
float offset; float size = outerSize;
if(!isFlatTop)
{
shouldOffset = row % 2 == 0;
height = 2 * size;
width = Mathf.Sqrt(3) * size;
horizontalDistance = width;
verticalDistance = height * 0.75f;
offset = (shouldOffset) ? width/2 : 0;
xPos =(column * (horizontalDistance)) + offset;
yPos = (row + verticalDistance);
}
else
{
shouldOffset = column % 2 == 0;
width = Mathf.Sqrt(3) * size;
height = 2 * size;
horizontalDistance = width * 0.75f;
verticalDistance = height;
offset = (shouldOffset) ? height / 2 : 0;
xPos = (column * (horizontalDistance));
yPos = (row * verticalDistance) - offset;
}
return new Vector3(xPos, 0, -yPos);
}
any reason why it generates the grid this way?
i read the docs and followed a guide
something to do with your code and math I would assume
Hi, so I have an animation event which is sitting on the animator of a gameObject called "EnemyBody".. this enemy body is the the child of the 'Enemy' gameObject, there is a function in the script which sits on the 'Enemy' gameobject, I need to access this functon from the animation event mentioned previously.
Alright well time to download Unity 2022.3.16f1
And if this doesn't work.
I don't even know...
Must be your y pos calculation. Why do you multiply it by .75?
Oh, it's supposed to be when it's flat top.
Debug your code then. Make sure you're not going the flat top path when it's not.
I think your hexes are just twice as big as the grid
And the overlap has z-fighting
that cant be it cuase there is room between the hexes
oh
i got it
yPos = (row + verticalDistance); >> yPos = (row * verticalDistance);
smh my head
On Unity 2022.3.16f1 and Splines 2.5.2, still crashes.
It might be doomed.
Does this package even work >_>
has it ever worked?
has anything ever worked π
2.5.2 worked perfectly fine for me on 2023.2.9 when i used it for a jam in february
Maybe I'm doing something wrong? I'm literlly just doing Create -> Draw Spline, drawing some points and then clicking escape when done.
Then I click around the knots and boom crash.
Spline doesn't even need to be closed.
I've seen the spline package crashing recently as well. I switched to the free Dreamteck spline package on the asset store.
I have to imagine this is a hardware thing at this point?
I've jumped across multiple Unity versions, multiple Spline versions.
All the same result, all on an empty URP Template.
On versions that others have said worked for them.
Maybe, I hadn't looked into it myself. Just switched lol
Is Dreamteck good?
Yep
Better than built in package?
I think so
We ride then.
Has anyone else had issues with transform.rotation.eulerAngles only returning a y value? The transform is rotating on the x axis, so I don't know why that is returning as 0
Uuuuh do you experience a bug where it throws an error when you delete a node?
It doesn't seem to be cleaning up its children when nodes are deleted.
okay, Unity is refusing to give me the x value of a euler local rotation that I can prove without has a non-zero x value
You are likely mistaken. My guess would be that you're assuming what you see in the inspector is the same as what you'd get via code
I have a script explicitly changing the x rotation of that transform
You'll have to post some code then
The first image is defining the rotation of the transform every time the player moves their mouse.
The second has the first debug log reporting that transform's rotation
They are both referencing the same Object
zRotation == aimParent
I have a theory as to why these are different
theory proven wrong
Also getting a zero for the x value of any transform rotation that I reference with that variable
anything that isn't ultimately parented to my PlayerCharacter has this same missing X value. I have heard that a rigidbody may cause these problems, but that makes me wonder what is causing my movement to still work
are you perhaps referencing prefabs on the object that is returning 0 for the x axis?
no prefabs
well, there is a prefab that has the same parent, but I don't see what that has to do with it
Hi, so i have this gameobject, i flip it using its scale when it hits a wall.. there is a child of this gameobject, I dont want the child to flip, any ideas?
Is this 2d? Sprite renderers have flipX and flipY properties
yes dis is 2d
how do i do that wit script?
i dont really care what i use to flip it.. its just that i dont want the child to flip
It's a bool as you can see in the docs.
Set it true and false
got it
wait no this doesnt work
bc its not a sprite
its a gameobject
with boxcolliders and stuff in it
how do i combat the problem of only the parent flippng and not the child
ok i solved it on my own.. for anyone wondering how to flip a parent without flipping the child..
- Flip the parent
- Flip the child
this unflips the child while the parent remains flipped
Sprites are gameobjects
What does it have, a sprite renderer or a mesh renderer?
isnt it only a sprite if it has a renderer?
It is only visible if it has a renderer.
What is the visible thing in the game?
Ah gotcha. So why flip it at all?
Instead of just changing the direction of movement I mean
ok so heres the exact hieracy:
Parent: Enemy
Childs: HealthBar, EnemyBody
I need the Enemy (the colliders on it) and the Enemy Body to flip while the HealthBar stays in the same direction
Ah, so are the colliders asymmetrical? Flipx would not have worked for that either way then.
The enemybody could have used it though, if it was just visual
If this is 3d, forward would be the direction you're facing where y would be a value relative to your forward direction in the y axis.
because its pointed upward
Can you screenshot that object with pivot mode set to local?
Because transform.forward will 100% not do that, so something must be wrong with your setup or code logic
You cropped out the hierarchy and inspector
anyone know why the movetowards line does absolutely nothing to the position?
{
transform.parent = primaryGrabbingObject.transform;
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
transform.position = Vector3.MoveTowards(primaryGrabPoint.position, primaryGrabbingObject.transform.position, Mathf.Infinity);
rigidbody.isKinematic = true;
Debug.Log("prim hand only");
}```
primaryGrabPoint and primaryGrabbingObject are at totally different positions btw, its just not moving the position for whatever reason
Why are you passing infinite as the max step delta?
Also, have you logged the two positions, and result of movetowards?
in order, primarygrabpoint.position, primarygrabbingobject.position, and the movetowards result (yes calculated before its actually moved)
however the transform's local position remains at 0 (well, relatively zero. as close to zero as floats get)
the movetowards result is expectedly working
So they are at the same position.
its just not getting moved to where it needs to go for some reason
and i used mathf.infinity temporarily because making the step be the distance didnt work either lol
You are trying to move it to where it already is
Ah, well log the thing being moved of course...
alright 1s
But your first parameter of MoveTowards is wrong though
First param and second are at the same position.
im trying to move a parent so that a child is at another objects position
first param and second are not though as can be seen by the log
The log shows the same position three times
no the first is different
Barely
im in vr so small number changes are rather large
just spacially
sorry not in good focus rn
im all brain fogged and this really simple issue is plaguing me lol
I recommend looking at the docs for movetowards
https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
The first param should be transform.position, as shown in the example code
oh true
i guess movetowards is not the method i should be using
originally i had just done
transform.position += (primaryGrabbingObject.transform.position - primaryGrabPoint.position);
but that was different each time i grabbed it
oddly inconsistent and i dont know why
That just adds the directional vector between those two objects. That doesn't seem like what you want either
ok let me explain a lil further
transform is the parent object here. it has primarygrabpoint as a child
the grabbingobject is separate. I want to move the parent so that primarygrabpoint is at grabbingobject.
what if i calculate the offset between grabpoint and the parent at start, then after i set the parent to be equal to the grabbing object, move it inverse to that offset
the primary grab point never moves, and i doubt ill ever need that functionality anyways
Then getting that directional vector seems right. Then move in that direction until the distance between the child and desired point is near 0?
I do not do vr at all, so it does sound like that is part of the complexity here
Vector3 desiredDirection = (primaryGrabbingObject.transform.position - primaryGrabPoint.position).normalized;
Hi, I have a bullet that goes out from an enemy gun and when it hits the player i want it to damae the player.. the problem is that the player has 2 colliders, a circle2D and a box2D.. so when the bullet hits, it does double the damage, how do i make it only do damage when it hits the boxCollider2D and ignore when it hits the CircleCollider2D
The damage logic is on the bullet script btw
unless you need the bullet to pass through the player, id just destroy it when it hits something
yeah it does get destroyed but it does 2x the damage.. cuz the player has 2 colliders
how is it colliding twice if it gets destroyed then?
wait is it a projectile or a hitscan object?
void OnTriggerEnter2D(Collider2D hitInfo)
{
Destroy(this.gameObject);
if (hitInfo.GetComponent<HealthBar>() != null)
{
playerHealth = hitInfo.GetComponent<HealthBar>();
}
if (playerHealth != null)
{
if (playerHealth.currentHealth >= 0)
{
playerHealth.Damage(bulletDamage);
}
}
}
here is the code for the damage
a projectile
I assume the circle collider is a trigger area? Make all the bullet and box collider non-trigger and use OnCollisionEnter
no both are non-triggers
You are using OnTriggerEnter right there. What is the trigger then?
Oh, the bullet?
yes
Why two colliders on the player?
cuz when i crouch i disable the top one (box col) and the circle col as the feet makes it easier to go up gradients
wait is this 2d or 3d?
2d
ok just making sure lol
lmao yeah
Ok. Not the greatest way to do that.
But simple fix, on the bullet script make a bool called hit. In OnTriggerEnter, do an early return if hit is true
Destroy isn't immediate, so the bool will be an immediate way to prevent it from running again
tbf i can just make the player take 1/2 the damage but thats a very botchy way and i dont wanna do that
def dont do that
lmao
whats an early return
basically return before the rest of the code is executed
ok ill try the bool thing
if (hit) return;
Right at the top
also makes it easier if you want bullets to go through the player in the future
for that i just make a layer and make it so that that layer cant collide through the collision matrix
wohoo it worked!
thx so much @full canopy and @spring creek
ya'll epic
:)
@spring creek this method finally worked
{
transform.parent = primaryGrabbingObject.transform;
transform.localRotation = Quaternion.identity;
transform.localPosition = Vector3.zero;
offset = transform.position - primaryGrabPoint.position;
transform.position += offset;
rigidbody.isKinematic = true;
}```
Nice! Glad you got it
i think some things were just executed out of order and me not understanding they changed each other because it all happens in one frame
I have this piece of code that starts the enemy shooting and animation:
if (cooldownTimer >= attackCooldown)
{
// Attack
cooldownTimer = 0;
anim.SetTrigger("rangedAttack");
}
There is an animation event in the animation which calls this function
void RangedAttack()
{
enemy.RangedAttack();
}
Then it calls the enemy.RangedAttack(); which is this function:
public void RangedAttack()
{
cooldownTimer = 0;
// Shoot Projectile
GameObject bullet = Instantiate(bulletPrefab, firePoint.transform.position, firePoint.transform.rotation);
Debug.Log("Instantiated Bullet");
bullet.GetComponent<EnemyBullet>().bulletDamage = projectileDamage;
}
Now the problem is that the enemy should shoot based on the cooldown timer, but its constantly shooting regardless of the cooldown time.. any guesses as to waht the problem is?
Do you mean to say that enemy.RangedAttack is being called randomly?
Or possibly that attack cooldown is zero. Where does the cooldown timer accumulate?
yes its being called CONSTANTLY.. like the bullets are supposed to be shot at 1 second intervals but its way faster than that
in update, its just cooldownTimer += Time.deltaTime
Maybe log the values and see if the if statement is true
If the if statement isn't true but it continues to fire, you can remove the if statement from your list of possible culprits.
I did a botchy job and its fixed.. good enuf for the dedline tmmrw lmaoo
Another problem... I used this piece of code to move the bullet, its in the Update method of the bullet script.. idk where i got this from but i have no clue why its transform.right, i want it to be whatever direction the enemy is facing
rb.velocity = transform.right * speed;
semicolon at the end is missing lmaoo
What does the error say? This is cropped so much it is basically useless to show
I am guessing it is not in a method?
Yep, not in a method
it has to be in a method
wtf is a method
a start or update or any other method
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
ok u shud prolly start frm the basics..
NO
i skip
i am super jenius π§
very smart
also why is it not printing still
Likely not attached to a gameobject, or logs are hidden
wait is ur script on a gameobject
scriptname doesnt match the class name, it wouldn't let you attach since they don't match
cant see anything in my console
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
precisely why u shud start frm the basics :D
how do you expect it to run then..
this is not a place for spoonfeeding and handholding
its not even part of the scene
by.. running
That is not how it works
yeah it only runs if its on a object
running how? its literally just a text file sitting in your folder
ic ic thx
ok i finally got to print hello world
LMFAOOO
i am so good π
fr fr
so how exactly does these scripts work, does it only run when the object it is under is loaded into the scene?
Yes
what exactly is considered "loaded"
unity is component based, any component must be on a gameobject to run
Being in a scene that is active
um, is there like documentation
for how everything works
and loads
Of course
I have linked the lessons twice
what is a scene, what makes a scene "active",
how to deactivate scene
etc etc
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
!docs
also this
which do I press first
Was gonna get the link, but saw you trying haha
go to pathways, do essentials
haha yea forgot what it was
then do junior programmer
everyhting I need to know and in-depth explanation on how scripts load, etc is in there?
once the language barrier is gone i should be able to do anything i want
learn and the manual
The first part yes, the second part is difficult to answer. It is up to you
learn gives you the hands on experience and teaching, manual if you want to learn how everything works behind scenes
API is for the methods/classes that are included (scripting wise)
game dev is one of the most complex and difficult types of software development out there. Be prepared for a struggle
You need to spend a lot of time learning, and finishing even ALL the unity lessons will not be enough
π
mk
sounds fun
ok so when the bullet is spawned in, it goes through this
void Start()
{
rb.velocity = transform.right * speed;
}
but the thing is it always points to the right and shoots to the right, even when the shooter is facing left.. how do i change that? btw i change the direction of the shooter by putting a '-' infront of its local scale
click on the shooter and see in inspector where the arrow is pointing. You arent actually rotating the object
yeah im not rotating im just inverting the scale
Are you spawning the object properly? if you are just instantiating the object it will spawn with its default transform
AKA always goes to the right
you gotta make it point to your actual intended forward
Its fine i solved it.. i remade my flipping machanics to rotate instead of invert scale and that seems to have solved it
So I am designing first person puzzle game, and I got stuck. So currenctly I have two interfaces with two types od items, ICollectable and IInteractable. I get them off item with raycast and invoke methods in it. How could I make this all one? Collectable hold different variables than interactable would ever need. Do I just have a Collect and Drop method in my PlayerController script? Or how would I manage this the best way?
Thx tho
One recomended approach was that I should create interface that is base and make those two inherit from it. Then I would still have CollectableBase and InteractableBase. With raycast I would check if current raycasting target is IItem and then check if that item contains an interface like IColectable.
You could do this, but whats the actual logic you're trying to do with this ICollectable and IInteractable? Adding a base interface here kinda makes it tedious because now you have to check which interface it really is. Whenever you want to add a new interface, everywhere that uses this logic now must be updated
If you're not really using these anywhere else, itll work fine
hi am new here
making a dockerfile for the first time to try run my project headlessly through linux but i keep getting this message
assistance would be very much appreciated
Well the thing is that to Collect and Drop have basics for checking if there is any item in the hand and then dropping it. I understanf what you are trying to say but I am stuck thinking about what should I do, for the best.
Previous approach just makes it really ease to check what to call.
it doesnt sound like this functionality should be on the collectable object itself
Collectable objects gets components like rigidbody amd collider. So for example to drop I have IDroppable interface which I implement in CollectableItem and then call it from PlayerController when key is pressed to GetComponent in hand ICollectable (IDroppable is parented to ICollectable), and then I call the method.
I think that I am just really stuck looking in one direction, and cant get out of it.
Should I just have collect and drop on PlayerController?
im not really sure of your exact setup, but still i dont think the functionality of "Collect and Drop have basics for checking if there is any item in the hand" should be implemented by the collectables themselves.
This would be better by the player controller
actually holding the item in hand would just be a matter of moving it to the players hand and possibly making it kinematic, whatever holding means in your game.
Yes.
So then having everything else in just InteractableItem base would make sense? But then again how would I know if I can pick it up?
if you use a base interface here, where the derived interfaces have their own method declarations, you're gonna need to check which derived interface it is. if (obj is ICollectable)
its not really the approach id want to go with, because im not a fan of having to check every possible derived type especially if this gets way more complex. But if this is simple enough you can get away with it
anyone here familiar with the unity xr interaction system? I just need to be able to get the gameobject that is interacting with any of the xr derivatives of the xrbaseinteractable. specifically, the xr grab interactable and xr simple interactable
#π€―βaugmented-reality or #π₯½βvirtual-reality might be the better place to ask
i did not know there were channels for vr
What approach would you choose then.
What is the difference between collect and interact?
But from your question, you should just check the type (or preferably an enum?) and send the component from your input to your player. Player checks for availability of slot and current item and then feedbacks to the component, if it gets picked up or collected or whatever you are doing with your interfaces.
It just feels like you are branching out too much on those interfaces
first thing is i would probably try to stay with IInteractable, because you are just interacting with the object whether its being collected or not. theres a lot that depends on your exact setup so its hard for me to suggest much more. Like one thing for pure simplicity could be just adding a OnInteractionEnd method which your collectable could implement so it can be dropped. Anything else can just do nothing with it. Not really the best pattern wise but that same could be said about needing to cast to check for every single derived interface.
I agree with bawsi. Keep it simple, an item can be picked up, can be used, can be consumed, can be equipped or what not. whatever happens on those methods can then be directed by an enum you set for each item for example. As soon as it gets out of logic and into metadata for each item, it should not stay within your code cause you gonna find yourself branching even more into weird spaghetti code to cover all of your needs just from code.
if you wanna see some fat garbage, this is how i handle effects (do X when Y happens), a similar approach to what i said above except with abstract class. Derived classes can implement these methods if they want. I have an enum which is used to say if these methods should be called.
Im not proud of it, yea itll log an error if i choose the wrong enum which is easy to do, but its so simple and works well.
I would take this in my own project any day over
if(obj is A)
....
if(obj is B)
...
// and more when more functionality is introduced
Thank you for your advice, time and help..
So if I understand you right I could make an enum in InteractableItem base which would be for now either Activatable or Collectable then we implement the IInteractable interface method Interact where we check for what item it is e(num type). Then we would define virtual void for each item. After that we create two derived classes ActivatableItem and Collectable Item and here I would override?
Where do you get your item from? Is it a database, is it a scriptable object?
For now, just a normal script. Will turn it i to scriptable object now that youve mentioned totally forgot.
Just be careful about scriptable objects being reset after every new app start
It wont if I system serializr it right?
No, it gets reset. You can store the state as a serialised object to json and on appload, load those json files and overwrite your default state. But the scriptableobject itself will ALWAYS reset when you restart the app/game. Just do not get confused by the editor, because in the editor, it just changes it and does not reset.
Alright but the approach would be good?
It depends on your setup, but yes. If you add items which would need more than just an enum, you could also just create "Tags" and add tags to the list of the item. But with my approaches, I always target the item data to be derived from a database or a list of predefined items (via SO or whatever). the code is just there for handling. You do not want to inherit "Apple Item" from Item class as its own class. Apple Item would be type of Item with the metadata name Apple for example.
Got ya.
So I i would add scriptable item to my collectableItem derived class that would have all the info? Sorry for that much questions.
Just searching for best solutioms that i can learn from.
Best case, you have either ton of scriptable object assets and they are loaded or stored on some kind of itemmanager or you have a database/file that holds all information about items and the manager creates those items as runtime objects from that information. Many ways how to do it
Thanks.
Hi, I am planing to crate a game with some terrain, I have been researching and I kind of like the terrain tool approach that the official unity terrain tools extensions offer
The think is that I would like to generate the noise and terrain at runtime using the noise generator and the terrain toolbox but I can't find a way to do that, any advice?
modify terrain data
you may need to rebake terrain collision which I'm not sure how it works
one sec
oh it's binary
for some reason, i can't access to hinge joint component of object hit by ray
its an fps game
the script is attached to the camera
im trying to make physically pushable door
that mouselookscript.sensX/sensY = 0 is just to disable camera movement while using/opening door
maybe something is wrong here?
no, like i can't change the value of target velocity
to clarify, when you set target velocity to a value does it automatically get set back to 0?
yeah
I read that it's a temporary variable. Look into how target force works instead. You can apply an angular force until you reach the desired velocity
If you're making a physically pushable door why would you need to set the target velocity?
what should i use instead?
as in what are you trying to do?
if youre making an animation you can honestly hardcode the animation
rigidbody apply angular force
hmm but wouldn't door just rotate around itself?
cause i don't think you can change pivot point of an object right?
You can with probuilder
But generally is easier to just make it child of another with correct offset and rotate parent
so do i use rigidbody for it or rotatearound?
you want a physicsally accurate door you want to use RB with Torque
personally would make sure my pivot is correct by using another object instead of rotate around
hmmm okay
I'm making a rhythm game where users can create/share beatmaps. inside the beatmap file is a link to the song's audio which will be downloaded for the user and played as part of the level.
are there any security risks behind this?
Unless someone finds a hilarious bug in the MP3/Vorbis/etc. decoder, no
But it could be used to be obnoxious
like distributing files that get flagged as malware
or downloading 100 gigabytes of garbage
uneless the audio is CC or Public domain it is also piracy in a way
the legal angle is more problematic :p
This is more of a proof of concept, when the time comes I'll pull off a geometry dash and restrict it to newgrounds downloads
I'll still need to tackle the problem of loading sounds at runtime though
oh ok if its testing purposes i would still use royalty free musics
iirc everything on newgrounds is π to use
use streaming assets or addressables?
streaming assets is just a way to copy files into your build folder
If you need to load audio at runtime, you just need a way to decode compressed audio
Unity has a way to do that through a web request, actually
maybe Fmod?
For loading dynamic audio, the only Unity way is to use UnityWebRequestMultimedia.GetAudioClip, since Unity does not expose its decoding, and the decoding it comes with is extremely limited.
Chances are if you allow user generated content, you have no choice but to either convert their audio at the time of uploading, or convert when you play them.
it's weird how it's only exposed through this one method, yeah
but you can almost certainly grab a C# library to do this
especially since you don't need super low-latency decoding or anything
you can just decode an entire song
I needed to do something similar and I ended up just embedding FFmpeg.
It's a different story if you are making a rhythm game for PC, but for mobile the Unity's audio has unbearable latency, and I wrote my own audio engine for that.
fmod also has remarkably high latency by default, weirdly
i had to go turn down the buffer size by half (still works great)
it was really obvious
Yep, because low buffer size can cause buffer underrun which results in audio sounding like it's tearing/glitching, so I wouldn't be surprised if the default is set to so high to be on the safe side.
Tbf for most games audio latency being 100 ms isn't much of an issue, it's mostly a problem specific to rhythm game genre. If you are lucky to get by with Unity/FMOD that's great, otherwise you almost always need to go down a rabbit hole of audio solutions, or even making your own.
it was more like 200ms lol
wait, that number is way off lol
the total buffer length is about 41ms by default
but I was having massive problems with audio latency before I changed the buffer size
and i'm not experiencing that now (after putting the size back to the default)
wack
time to investigate that

the default buffer length was 512, and I had turned it down to 256
sorry for disturbing you again but.... the door spin around the parent object, not rotate LOL
I kinda pitched in half way in, what is your end goal here vs whats happening now, and what is the current setup?
Hi, I have a prefab with a grid+tilemap and am trying to use the tilemap within the prefab in an edit-mode script.
Script: https://hastebin.skyra.pw/leqarudidi.csharp
This code instantiates a copy of the tilemap with the tiles in them, and they appear as children of the Tilemap component in the script. However, the tilemap itself seems to be empty. I'm also sure that I'm drawing to the correct tilemap.
i just want a door that rotates :P
lol
that can mean different things
also send current !code in a link
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
and show the scene view on how you setup the door, each gizmos shown
https://paste.myst.rs/3y6arldx
why does my rigidbody / vehicle seems to be rotating (yaw) relative to world axis?
a powerful website for storing and sharing text and code snippets. completely free and open source.
dont crosspost
I dindt kknow wiich channel it fits my problem...sry...
that torque looks wrong
should I use this one?
just stick to one, doesn't matter which
if its a code question then it goes in A code channel
ok
where / why?
where did i do wrong tho
also * Time.deltaTime you should never multiply mouseInput by delta time
mouseInput is already framerate - independent
your door is setup wrong
you have to rotate the Parent not the child, make sure thats happening
its a gamepad button / A or D key, that still applys?
gamepad is irrelevant
yes thats is correct the script is attached to the root gameObject
I have no Idea why you are replying about someone else's issue
I'm literally helping @golden sinew
LOL
omg im so sry
yup know i see it so sry
its fine lol looks like in #π»βcode-beginner boxfriend already gotchu
yup sry about that to
soo how do i do it? i thought i was rotating the parent not child :P
start by printing the name of the Rigidbody before you rotate it
so be sure its parent
start from basics, work your way up the issue
hmm okay
Debug.Log(b.name)
Question:
I'm working on a stealth system where a capsule basically patrols an area and rotates. These work on a coroutine. We wanted to expand upon this and have it look towards and move towards the player once it's spotted them. When stopping the coroutine it teleports the patrolling capsule however. Anyone have any ideas on how to avoid the stopping of coroutines from affecting the patrolling capsules position?
why would stopping coroutine affect anything with positioning
I dont know it just does π
then you have to post the !code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
it sounds like you're just setting the new position instead of moving it to that new position
how
that was not in response to your issue
XDD
second time today lol
i fell into the trap as well lol
its a busy morning
did you print what I asked?
doorObj.transform.parent.position * mouseX this to me looks wrong though
it would probably just be transform.up * speed
ok
@golden sinew btw you dont need rb on the child, pretty sure the parent already makes child door collider as part of its rb
no reason why you can't put your own collider on root too and keep the mesh for visuals
transform.up broke all the code :/
yeah that looks like better option XD
yeah idk torque makes sense for other stuff, this would not be it lo
oh gifs aren't allowed :((
Is a bad practice using cds like this? Because if the game has been running for too long the float variable wont be able to save the value of Time.deltatime, isnt it?
that condition doesn't make a whole lot of sense. are you sure you don't mean to be using Time.time instead?
yeah my bad sorry
but still the question is the same
but yes, around 2.7ish hours into the game, you may start experiencing more floating point inaccuracy issues with that as you lose precision
so how would it be the best option to do this?
that isn't to say that you absolutely will though
and using this method for cooldowns and timers and stuff is a perfectly valid option
if you are worried about that convert Time.time to a TimeSpan
IT WORKED!!
but i used rotatearound instead
I mean its fine, it just won't be physically accurate
For some reason, my gyro control script is no longer working.
The player just looks at its feet. else is not triggering so there is gyro support.
{
rot = new Quaternion(0, 0, 1, 0);
gyroEnabled = EnableGyro();
}
private bool EnableGyro()
{
if (SystemInfo.supportsGyroscope)
{
gyro = Input.gyro;
gyro.enabled = true;
return true;
}
return false;
}
private void Update()
{
if (gyroEnabled)
transform.localRotation = gyro.attitude * rot;
else
transform.localEulerAngles = new Vector3(0, -90f, 0);
}```
put debugs then
Why are you manually crafting a quaternion like that
Is that Quaternion even valid?
apparently its this Z : 180
Quaternion.w can never be 0
weird apparently its a valid rotation if you input it in the inspector see above screenshots
or is it maxing out at 180?
not sure but the rules of Quaternion math is w > 0 and <= 1
Anyone good with laptop specs
dang well you got me there, I know nothing of quaternion math. Ill stick to my eulers π
Quaternion math ain't that difficult if you don't mind your brain leaking out of you ears. Mine did that many years ago
haha Yeah mines been lost somewhere at some point
#1157336089242112090 has a few threads people asking laptop question
a code channel is not a fit for that
unless Blender is doing a different flavor of quaternion math, W is in [-1..1]
ah, of course: i can just copy a quaternion out of the inspector
indeed, a 180 degree Z rotation winds up producing [0,0,1,0]
so, it's a valid quaternion...but i'm not sure why you'd do that (:
hey
Why is it so hard to make games compatible with apples stupid self
apples are fruit, games are not
The company sorry for the confusion
iOS games
What is the difference between this type of documentation
// Explanation
And this type
/// <summary>
/// Explanation
/// </summary>
I read that the bottom is XML documentation but that doesn't give me much info
mhm they make it diffcult to do anything
And it sucks because thatβs where the iPad kid money is but is there any easy way to implement it
// is better for quick comments or memos, Summary is for generating documentation,API, clearly explains what each function does, also its formatted nicely. It also shows you in the IDE a description of it with summary and maybe examples, links( obs this is oversimplified)
Hi guys im changing the value of the currentLevelForHUD through another script then this value goes to on enable missions.transform.GetChild(currentLevelForHUD).gameObject.SetActive(isActive); problem is currentLevelForHUD remains zero i have debugged the code the value is successfully being changed but in onenable its just remains zero
https://paste.ofcode.org/itT7PSKah2heFFBVQXx4FS
Always prefer <summary> since it has semantic meaning in code for anything that might interpret it. That could be some sort of parser or just your IDE showing function explanations on hover.
Is the documentation supposed to stay in the script or is there a way to extract it to a documentation file?
I made a package for a camera system which has different toggleable features, where I documented it using /// <summary>
Keep it in a script. If you want, there's always tools for extracting documentation. Google "c# documentation tool"
But I don't see why you'd need that
does anyone know if there's any way to filter or sort by filesize in the project window?
perfect, thanks π
is this a code question?
I have no idea where is a more appropriate board to ask
you could probably code an extension π
I'm talking about the unity project window
So either #π»βunity-talk or #βοΈβeditor-extensions
so you can open for example every wav over 50mb to set certain inspector settings
not that I know of, but you can > Show in Explorer >Sort By >File Size
the unity project window is basic af
isn't it
Sorry for trying to help. Not sure who is not chill. But best of luck
which is weird, maybe people here use extensions?
navarone was a bit 'direct', but I'm the same whenever I help a lot of people constantly
ctrl + K
it gets tiring to talk with a filter
the searchbar has a "query builder" , I bet you can find the one fore size etc.
I only saw in the docs label and type
but yeah I did wonder that
no wait
there is
thanks navarone you got me to it
aye goodluck. You can only use bytes for filesize so gotta get a converter out
yeah hahah add zeros until it catches things
you can't multiselect to change properties on multiplies but it can at least help me to catch the obnoxious wavs that I need to load in background causing stutters
Okay, I need help designing/implementing an algorithm.
I have a series of non-uniformly shaped objects and I need to place them without overlapping on a tabletop. I've already got the object's bounding boxes calculated, and can position them on the table by the center point of their bounding boxes. So, we can think of it as "I have a series of rectangles of varying unknown sizes", and I need to position them inside of a larger rectangle of unknown size, one at a time, as they're spawned in. I don't have any particular needs to maximize the space between objects, so having one object in the far corner of the space is fine if that's what the algorithm would spit out.
I'd also like to add in an optional "padding" parameter that'd make sure the objects are no closer than a specified distance.
The naive way to do it is to start at X/Z corner of the table plus the extents of the first object, plus the padding, and then add the extents to the offset and recurse, but that would lead to less than optimal use of space. Consider this case, where we have the blue and red objects placed already, and try to place the purple one. Optimal space would put it above the blue box, adjacent to the reds, but the naive algorithm would put it flush with the bottom edge of the table, next to the blue box.
Oh God I just realized this is just the knapsack problem and it's NP Complete
I guess that's why I've been struggling to find an answer: there is none
This is basically just texture packing, and there are plenty algorithms online for it.
Before that realization, I was going to suggest approaching this like building a spatial tree. When you add a rectangle onto the table, split the table into quads. To place an object, look for the smallest quad that can fit it and put it in there.
A very basic algorithm is:
- Keeping a list of rectangles which represents available empty spaces.
- The list obviously starts with just one rectangle of the entire space.
- When trying to place a new item, find an empty space larger than the item.
- Remove the empty space from the list.
- Put the new item in the top right corner of the empty space.
- Now the empty space has an
Lshaped unoccupied space. - Split that
Linto|and_. - Put
|and_into the available empty spaces list. - Repeat until all items are placed.
That could work, but I'd need to decide on how to partition the space into quads properly, which itself would be a challenge
Hm, let me try this. I supposed it wouldn't matter much which way I split the remaining area, it would still be close enough after everything's placed.
Yeah it doesn't matter which corner you put the item into the empty space, and it doesn't matter how you split the remaining L.
For texture packing, there are a lot of things you can do to optimize it, eg the orders of items, the orders of empty spaces, etc. But in your case seems like you don't need to care about any of that.
Can we make changes into scene 2 from scene 1.
like what? thats vague
ofc something like a singleton can interact with both and change stuff
Like I want to throw some object into scene 2 from scene 1. And if I go into scene 2 that object should be there.
you can probably put it in a DDOL
What is ddol.
its a special scene that lets you put objects that aren't affected by scene changes destroy
I know ddol then. But
Ok will try.
I am making a portal from scene 1 to scene 2 and now I am able to see scene 2 from scene 1.
Ddol didn't came into my mind. Will try that.
Guys, how can I compare the value of an int with that of a list with different values ββand if some are the same then return true
return someListOfInts.Contains(intToCheckFor)
This worked perfectly by the way. And it's still much faster than the system it's replacing (spawn the object, check for collisions, nudge object, recurse) so it should be clear to go. Thanks!
ty β€οΈ
Is Application.persistentDataPath the correct x-platform path for writing a game's persistent data? Over the years, and on different platforms, I've seen/used lots of variations and hacks. Checking the docs today ... it looks like that path is broken at least on Linux (where it's a system-wide shared folder), most mainstream platforms it's a correct user+game specific folder, but notably mobile it appears to be a fallback folder that will only be correct for some (not all) API calls
You mean that folder can be hacked. And the saved data is visible?
Wdym by the mobile point? AFAIK, both Android and iOS essentially have a virtual file system for each app, and you can only read/write within that. Applicate.persistentDataPath points within the container.
I don't know what you mean by "some (but not all) API calls"
also, the path in the docs for Linux is a bit misleading
It's really ~/.config/unity3d/CompanyName/ProductName
so it works fine.
"hacks" as in "hack job": bad or janky solutions
Yes right fen.
i cant seem to figure out why my ui items get messed up the 2nd time this ui pops up during runtime.
If I adjust the window size even by very little, it automatically fixes itself. If i enable and disable the canvas gameobject, it fixes and if i enable and disable the canvas scaler compoenent, it fixes. I'm not sure what's causing it though
First image is of it being bugged, 2nd image is me resizing the window and bringing it back to size of first image and it's fixed. Also an image for what the canvas looks like
I found some code to help me with vector comparisons, but I'm missing a package. It's offering 3 different ones for "Mathutil" which one do I need?
How should we know? What is "MathUtil"? Where did you get the idea to use that?
Use whichever one being used in whatever code you are copying or referencing
(in this case that would be none of the 3 options anyway, since Unity does not support NuGet packages)
I wasn't sure if it was something commonly known or not, that's why I asked.
I got it from this thread from one of lordofduct's comments.
https://forum.unity.com/threads/comparing-two-identical-vector3-returns-false.327128/
I realize now it's one of his own classes.
Sorry I asked.
Should probably do as the first answerers did, which is by not using == to compare vectors. They're made of floats, which can suffer from precision issues
Yeah, I've been getting hit by them almost randomly.
I tried comparing the square magnitude instead but that also has the same issue sometimes.
Consider constructing a direction vector from the two vectors to compare, and checking whether its magnitude is lower than some threshold
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
while (diff > .001)
{
//Move
}
diff = Mathf.Abs(foo.sqrMagnitude - bar.sqrMagnitude);
This is what I changed it to, but sometimes it says there's practically no difference even though the two objects are 1.5 units away, so it's very noticeable that it's not in the correct position. So I'm exploring more options.
Hey all,
Sooooo, having a brain thing.
void PlayExplosion()
{
Debug.Log("Play Explosion");
GameObject newExplosion = GameManager.Instance.enemyExplosionPool.GetPooledObject();
ParticleSystem particleSystem = newExplosion.GetComponent<ParticleSystem>();
Vector3 explosionLocation = new Vector3(transform.position.x, transform.position.y, transform.position.z);
newExplosion.transform.position = explosionLocation;
particleSystem.Stop();
particleSystem.Clear();
newExplosion.SetActive(true);
particleSystem.Play();
}
Haven't use Shuriken in forever, so I'm not sure what I'm doing wrong. Everything here is working, except for 'resetting' the particle system back to 0 so that it plays from the beginning on 'spawn' from pool.
Anybody got any pointers please?
That distance should be calculated like (v1 - v2).magnitude (or sqrMagnitude), subtracting magnitudes of points in space like that doesn't make much sense
Ah, great. So it's probably fine then
In my experience: canvas scaler is horribly buggy. A lot of Unity classes are badly written when it comes to scales and scaling (lots of places the authors 'forgot' that objects sometimes have scales other than 1/1/1). I avoid using it as much as possible.
Your case looks like your anchors are slightly wrong, I would check: are you configuring them from UI purely, or are you configuring them from code? If from code, you might not be handling the canvas scale values correctly
Adjusting the window triggers a full relayout of UnityUI which corrects a lot of the buggy UnityUI classes
ah is there a way to force this relayout through code maybe? :o
the buttons and stuff are there statically so not generated/adjusted from code.
What's the correct approach to document two methods with the same name but different parameters? <inheritdoc> doesn't work because it takes the wrong one (since they have the same name). Should I just copy+paste the same summary from the first method?
I just duplicate it
I don't know what you mean. You said I shouldn't subtract magnitudes of points in space, but I don't know how that differs from your suggestion: "(v1 - v2).magnitude".
Do you have any ContentSizeFitter components that are showing a warning?
you're subtracting the points, then taking the magnitude of the difference.
That's very different from taking the magnitudes of the points, and subtracting those
taking the magnitude of a point just tells you how far away from 0,0,0 it is
which we don't care about
My version builds a direction beforehand
Meanwhile yours took the distance (magnitude) of the points themselves, which is the distance between the point and the world's origin (which is what a point is, the result of applying a vector to the world's origin)
nope i do have this error that started show up recently but i dont think this has anything to do with it haha
This would not be in the console.
oh
It would be displayed on the ContentSizeFitter's inspector.
isee what u mean
If so, that's why you are having problems.
i dont have contentsizefitter components, dont think so... this is one of the buttons that was messed up
I'm going to need to see your hierarchy to understand what's going on here.
also, to check, search your hierarchy for t:contentsizefitter
Example:
Vector2 v1 = new(1, 3);
Vector2 v2 = new(3, 4);
Debug.Log(Mathf.Abs(v1.magnitude - v2.magnitude)); // 1.837
Debug.Lof((v2 - v1).magnitude); // 2.236
also, this is a UI problem, so please post this over in #π²βui-ux
oh i do have them for a separate panel inside the gameover canvas but its disabled
should it be affecting stuff even tho the object is disabled?
No, and that's also fine
ContentSizeFitter is an issue when it has a parent with a layout group
you wind up with weird behavior as it fights with its parent
(it will display a warning when you do this)
aha i see
Also, taking the differences of magnitudes would disregard directionscs (-5, 0) (5, 0)``````cs //~0 //sqrt(10)It'd make no sense.
your scroll view's Viewport doesn't have a layout group (because it's only job is to be a fixed-size region that masks the Content), so that works
Show me the full hierarchy for one of these buttons in #π²βui-ux
oki
That is a significant difference between the two since precision is a requirement for my game. Thanks for posting the example, I was trying to put Mathf.Abs in front of it so it wouldn't compile.
So now it'll look like this:
while (diff > .001)
{
//Move
diff = (bar - foo).magnitude;
}
Although I was checking for sqrMagntitude before. Am I going to have to change what the while loop is looking for if I switch from sqrMagnitude to magnitude?
no, not really
To make it exactly the same, you'd just adjust the threshold you're comparing to
0.01 sqrMagntiude is 0.1 magnitude
but it'll be very close already
so, yes, but also no π
Ha, okay. Magnitude should work then, thanks.
sqrMagnitude is magnitude without the (not so expensive nowadays) square root applied internally
It's marginally faster
You might as well use it if you're just comparing against a constant
It's working beautifully. Before objects would randomly get stuck if the floating points were barely tweaked, or if the game object movement speed was slow. Been fighting this for like 3 days.

public static bool CancelAction()
{
return Input.GetMouseButtonUp(0) || (Input.GetKeyDown(KeyCode.Tab) && (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt)));
}
I wanted to do something like this to "cancel" an action that involves pressing and holding, because currently if I alt tab out, the GetMouseButtonUp event doesn't fire. However, this still fails to return true when I hold alt then press tab. Any other idea for this?
what kind of "action" are we talking about, and how would this cancel it? Likewise, when would you actually call it?
If you want to do something when the game loses focus you can use this https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationFocus.html
On losing focus will probably work for me, I'll try it
Yep this worked exactly as I wanted, thanks
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
can anyone help me out on why this is happening?
how is this null
its a function that runs whenever a static action on another script is invoked
Maybe describe what you're trying to do and what's happening instead.
static action
you're not unsubscribing from it
so... whenever an enemy dies, it calls a static function on another script( an Event bus) that fires an event and this is the part where i listen to get, get the data from the enemy to sum into my levelling system
you need to make sure that whenever anything that subscribes to that event is destroyed it then unsubscribes from the event
and whenever i debug this, the enemy gameobject still exists, but locals show me that the own object i am at is null
otherwise you get NREs
uhmmm okay
and this is even more important if you've gone and turned off domain reloading
yeah i get that, but i just checked all the references and im actually unsubscribing to it
i dont even destroy the object, its all pooled
show the code where you subscribe and unsubscribe from the event
okay well first, !code
second, where is that DisableInputs method called from
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
OnDisable
that object doesnt get disabled yet tho
You'll need to use the debugger to figure out what isn't unsubscribing π€·ββοΈ
You subscribe in 3 places, but unsubscribe only in 2. It could be that some object is subscribed several times to the event
Thanks guys, you pointed me in the right direction but it wasnt it.
The problem was that i was calling a function that was calling that event whenever i dealt damage, even when the enemy was already dead.
So i guess i have to check if an enemy is alive before actually killing it
That's basically what boxfriend was saying
yeah thanks for the help!
I just started messing around with the Splines package and I can't figure out how to access the additional properties of a Spline Container: Int Data, Float Data, Float4 Data, Object Data. Like, it looks like I should be able to name and access these Int Data properties but I can't find out how from the docs or from asking Unity Muse. Maybe y'all can point me in a direction? Here's my inspector.
hey everyone! im making a game similar to omori / pokemon in the type that you explore an area until you run into a transition wall, where it takes you to another scene.
https://gdl.space/gekeguyato.cs
the difficulty im having is what to put in the very last else if statement, which will probably just call another script because it will be a lot of code. I want to know the best way to tell the SceneManager what scene to load based on where you are. my best ideas so far are to tag each loading zone with a different tag(will probably get tedious), or to have it detect what scene its on and then use only a couple of tags that describe where a general set of loading zones might be in a scene(north, south, east, west, house1, house2, cave1, you get the idea). it would use less tags but still be pretty repetitive. anything that uses tags will have to change the way the code checks the tile anyway. anyone have any insight that might be better?
the idea is that once the player tries to enter the white square(tagged "Transition") the raycast will see it and then call another script that manages which scene it will transition to
Use ScriptableObject to represent each individual scene instead of Tag. Something like (pseudo code, will not compile):
[CreateAssetMenu(...)]
public class SceneDefinition : ScriptableObject
{
[SerializeField]
//Use Addressable to manage scene
private AssetReference sceneAssetReference ;
public AssetReference SceneAssetReference => sceneAssetReference;
}
public class SceneLoadingTrigger : MonoBehavior
{
[SerializeField]
private SceneDefinition sceneDefinition;
public void OnTriggerEnter2D(...)
{
GameFlowManager.Instance.LoadScene(sceneDefinition)
}
}
public class GameFlowManager : MonoBehavior
{
//Create a Singleton or us a pattern such as ServiceLocator
...
private List<...> loadedScenes = new List<...>();
public void LoadScene(SceneDefinition sceneDefinition)
{
var handle = sceneDefinition.SceneAssetReference.LoadSceneAsync();
loadedScenes.add(handle);
}
}
thank you! this ScriptableObject container is new to me
Hey, can anyone help me with this function?
https://docs.unity3d.com/Packages/com.unity.mathematics@1.3/api/Unity.Mathematics.noise.psrdnoise.html
First, what does "rotating gradients" mean?
I assume i means the traditional meaning of gradient in mathematics, but what does it mean to rotate it in this context?
Also, the x and y partial derivatives represent what? Just what a normal derivative would represent? Why is it given as a partial derivative?
im not sure about what it means by rotating gradients, but the derivatives from what im looking at are partial because its a float3 function(3 variables)
i assume it just means the gradient is rotated in space, like if you took the noiise texture and rotate it
I suppose it's very ambiguous. To me because it's plural it means the gradients as in the derivatives of the 3D vectors of the graph. Is there anywhere I can look at the code for it? I know there's c# reference code for Unity, but I don't think this package is included in it.
ah ok thanks. I never formally learnt partial derivatives, so my knowledge on them is shaky. It still means the slope in that direction, right?
i wont lie i took vector calculus back in 2022 and dont remember much either
ooh thanks
yes I was looking at it right now
I wonder why they don't have any noise function that includes gradients or partial derivatives for perlin noise
so i think i almost understand everything. i make an asset for each scene of the game with a specific name, and call it in the trigger for each loading zone?
oh tnx
I beleive they have pins there that can help
I need some more help. Here's what I've got so far:
3 scripts: a SceneDefinition ScriptableObjectDefinition, a TransitionManager MonoBehavior, and a Player Monobehavior.
2 Scriptable Objects that coincide with 2 different scenes
What I want to happen:
The Player script detects that the player has tried to enter a Tile gameobject with the "Transition" tag. This calls the TransitionManager gameobject to transition the scene to the correct scene as defined by the ScriptableObject that has a string attached with the Scene Name that that specific gameobject will load to.
https://gdl.space/ofeqatitug.cs
The issues I ran into:
I have no idea how to reference the scriptable objects. this is what ive got so far. im really stuck
Referencing scriptable objects can be done the same way you reference any other asset
Direct serialized references in the inspector
hey does anyone know how i can get momentum movement for my 3d unity game? im trying to make a game inspired like lethal company and love the movement. Any tips?
Use a Rigidbody
im new to unity may you explain?
I do this on the gameobject tiles, but the issue lies in the way the Player script finds the TransitionManager. I can't directly call the TransitionScene void because if I make it static I can't change which Scriptable Object to use
Wouldn't it just be whichever one you collided with or whatever?
any help anyone?
Like why one earth are you doing this?
FindObjectOfType<TransitionManager>()
You should be using the one your Raycast hit
No because I can't figure out how to access a variable from a script component of the "hit" gameobject from the raycast
I'm not sure if thats possible
It would take too long. Look up tutorials. You either use the physics engine or simulate momentum yourself
Or course it's possible
How can i do that?
Ever heard of GetComponent?
yes, but I couldnt find anything in it that would let me access a script components variable
Your code is literally already accessing the collider AND the GameObject
If you know about GetComponent, I'm not sure what you think you're missing here
E.g.
TransitionManager tm = hit.collider.GetComponent<TransitionManager>();```
that gets the script but how do i get the variable from it?
Same way you get a variable on absolutely anything
With the . operator
But why do you need a variable?
You just need to call the function
I can't just call the function unless its static
Wrong
You can call the function when you have a reference like this
tm.TransitionScene();
How do you fix this wierd striping issues of blocks in a voxel engine? They don't show up like this in the paused state so why is it happening during runtime
it happens in the built version of the game too
here's how im rendering textures and UVs
This doesn't really tell us how you're rendering things.
Are you making one big mesh or are you using individual renderers for each voxel?
Is this not the code that renders the meshes?
sorry, it's borrowed code
Is this what you're looking for?
because the entire chunk is 1 mesh
{
int xCheck = Mathf.FloorToInt(pos.x);
int yCheck = Mathf.FloorToInt(pos.y);
int zCheck = Mathf.FloorToInt(pos.z);
xCheck -= Mathf.FloorToInt(chunkObject.transform.position.x);
zCheck -= Mathf.FloorToInt(chunkObject.transform.position.z);
return voxelMap[xCheck, yCheck, zCheck];
}
void UpdateMeshData(Vector3 pos)
{
byte blockID = voxelMap[(int)pos.x, (int)pos.y, (int)pos.z];
bool isTransparent = world.blocktypes[blockID].isTransparent;
for (int p = 0; p < 6; p++)
{
if (CheckVoxel(pos + VoxelData.faceChecks[p]))
{
vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 0]]);
vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 1]]);
vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 2]]);
vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 3]]);
AddTexture(world.blocktypes[blockID].GetTextureID(p));
if (!isTransparent)
{
triangles.Add(vertexIndex);
triangles.Add(vertexIndex + 1);
triangles.Add(vertexIndex + 2);
triangles.Add(vertexIndex + 2);
triangles.Add(vertexIndex + 1);
triangles.Add(vertexIndex + 3);
}
else
{
transparentTriangles.Add(vertexIndex);
transparentTriangles.Add(vertexIndex + 1);
transparentTriangles.Add(vertexIndex + 2);
transparentTriangles.Add(vertexIndex + 2);
transparentTriangles.Add(vertexIndex + 1);
transparentTriangles.Add(vertexIndex + 3);
}
vertexIndex += 4;
}
}
}```
this is the part that renders the triangles
Just confirmed, it's 1 big mesh for the chunk alongside a mesh filter
But I don't see anything that would potentially lead to inaccuracies like seen in the scene
a good solution about this kind of agnostic game state managers is to have a static reference to itself
so when the manager initialzies, it saves a static reference to itself in the class, that way you can access it everywhere
You're talking about a Singleton, which this thing is not
easiest way to implement singletons in Unity, and imo one of the best way to handle any kind of managers that dont need to know entirely about the game state (Like a music or SFX manager)
yeah I know but the way they defined their stuff , the best way to handle this is with a singleton imo
or have that scriptable object reside on a singleton
I personally prefer having singleton managers that survive through the game loop instead of having these managers constantly create/destroy themselves
it also asure no race conditions or weird scene setup weirdness happens
i couldnt figure out how to have a single gameobject be a manager for it, instead each loading zone has its own instance of the script
best way is to have an init scene
that loads all of your managers that will not die and survive the entire game loop
public class SingletonManager : MonoBehavior {
public static SingletonManager Instance;
public void Start(){
Instance = this;
}
}
the loading zones are gameobjects that ill put in each scene where the player has to walk to trigger it
now you can access that singleton manager from everywhere with SingletonManager.Instance
each one of those white tiles has a transition manager script
i tried to do it with a single empty gameobject that would manage it but i couldnt figure it out because it had to be a different SO for each area
it seems to me you dont want to actually do that
oh is what im doing better?
like, instead of having to asign a SO to each area like that, it seems like you want an SO that holds references to all of your individual SOs
with a Dictionary or something similar
or just something else to attach to each loading zone tile thats why originally i wanted to make a different tag for each scene
because i dont want to have so many scripts running but i guess it wouldnt matter because they dont do anything unless theyre hit by the raycast
and only one would be hit at a time
oh, this reply basically says what you should do hehe
yeah but im not experienced enough to figure it out yet
im not sure what an Adddresssable is
i found it in the packages but i didnt figure out how to use it
you can skip that and instead just work directly with an scene reference