#archived-code-general
1 messages · Page 40 of 1
I haven't used it but theres a new-ish Animation rigging package that could be used for that kinda stuff
and for this enemy i want to use an inverse kinematics approach, to let him actually grab on to stuff
i was thinking more of a DIY approach rather than a package, but i will look into it
I mean you would still have to do a bunch of coding
If youre good at trigonometry, roll your own IK
There are some hinge overrides and tutorials about how to do IK in unity I would look into
well yeah but i was more wondering which way i should go about it, i know how to make basic simulated IK but you can do it in alot of different ways
joints, no joints, rig, no rig, even physics based or non physics based
from how i see it, at a basic level, IK is about having the end point and calculating it from the end back to the start
so from that you could do it a million different ways
alright
[SerializeField] Vector3[] Placement;
[SerializeField] GameObject[] Objects;
// Update is called once per frame
void Start()
{
Spawned();
}
void Spawned()
{
Instantiate(Objects[0], Placement[0], transform.rotation);
Instantiate(Objects[1], Placement[1], transform.rotation);
Instantiate(Objects[2], Placement[2], transform.rotation);
}```
Hi. this works btw haha sorry but this seems unprofessional. Is there a short way to write this or is this the only way?
Use a for loop
Hi guys, is it necessary to install net. sdk if yes where
should I install it in?
only if it's part of your IDE configuration guide
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Hello
myAudioSource.PlayOneShot(myAudioClip) is not playing the sound immediately there's a small delay
is there another way to play the sound without delays?
Is there a delay in the audio?
PlayOneShot shouldnt add any delay
It could be in your audio clip, make sure that it has no silence at the start
You also might just be experiencing input delay, especially in the editor
im getting errors from scripts that have been deleted, has anyone encountered something like this?
its related to the input system
no like
the scripts are giving errors everytime an input is pressed
even tho those scripts dont exist anymore
its weird because the scene gets completely reloaded
and everytime it reloads the errors multiply
sounds like you subscribed some event listeners and never unsubscribed them
pretty common error
if you reload the domain it should go away
at least until you do the same thing again
but the object holding the events gets reloaded as well?
you sure? Show the code.
are the events static?
therye unity events on a player input component
go into the unityevent
make sure you removed the listeners
for the nonexistent scripts
wdym
if you have invalid event listeners configured in the inspector, they will cause errors
^^
and what are the errors
basically every input i have gives a similar error
just a second i reloaded
oh well
unsubscribing worked
Basically you are subscribing to the input actions asset backing the PlayerInput
you are sidestepping PlayerInput basically
and since you are holding references to those InputActions, the asset sticks around too
so the actions stick around as long as therye subscribed?
Hey can i ask a question here?
because i have been stuck on something for a few hours now
yes you can ask a question here
alrighty
So there are actually 2 questions
1 is, how can i properly quit the app when i upload the game to the Google Play Store and the IOS App Store? Because neither application.quit or killing the task work there.
- i am remaking a small version of playerprefs for saving data i really want to keep, but besides that how can i access the script anywhere without using static classes or references or singletons? Because namespaces dont work (i cant reference the script because it's not in the scene, and making it static doesn't work either because i save data using private strings and stuff)
alright thanks
hi, how would someone go about implementing acceleration/de-acceleration for fps movement?
woudnt i need to directly apply it to input itself? which seems kind of wrong
i don't really know what that is... soo yeah
but i got this with arguments and methods (except data processing)
No, acceleration / deceleration has to do with momentum of your character
you'd track the current velocity of your character, and modify the velocity over time based on the current input data each frame / physics frame
i am using a character controller not rigidbody
yes, what I said applies even more so
With Rigidbody the physics engine does the velocity stuff for you
With CC you will have to do it yourself
Hi, This might sound like a dumb question but how do i make the transparent parts of the leaves on the tree not cast shadows?
i see...but there is one more thing that confused me
in order to detect if the player is trying to move would i have to read from input directly?
oh.. uhh i cannot use it in any of my scripts, the question is how can i use them in other scripts? Like the actual unity playerprefs
like....
Yakanashe.BinaryStuff.SetFloat("idk", 1.23);
//or...
BinaryStuff.SetFloat("idk", 1.23);
i dont know how to achieve this, and adding the namespace doesnt work
I have an issue with some vectors right now. I want to get the vector pointing where the player is looking but ondrawgizmos seems to show this is not what I'm getting at all even though the code seems right to me, does anyone know the issue?
https://i.imgur.com/ajP0hCi.png
https://i.imgur.com/318x1yX.png
You can see the green line is supposed to be pretty much where the player is looking but instead its tied to the world origin, any ideas?
usually i would have an enum that switches between moving and idle based on charactere velocity
you have to read input to get input data yes... What's confusing about that?
but that wont work
The PlayerPrefs methods are static
wdym
uuhh well then i don't know what to do anymore, i'll poke my scripts with a stick and hope it works
you're passing a position and a direction into DrawLine. DrawLine expects two position vectors
If you want to model yours after PlayerPrefs, you would make yours static too
it just seems wrong to say if (pressed WASD) accelerate
idk feels hacky
but then how can i encrypt or decrypt it using the other method in my script?
what's hacky about that
nothing i guess
the encyption method owuld also have to be static, or you would need to have a reference to the instance to call it on
sorry if i came off as a little bit racist btw, i appreciate your help
welp this is gonna take longer then expected, but i'll fiddle around with what you said and hope it works, thanks!
i will see how it goes
how do I get the position of the forward vector then?
forward vector doesn't have a position
it's a direction
You should either calculate a new position in that direction from the origin position, or use DrawRay which expects a direction vector instead of a position vector
I fixed it by making the second field position + forward
yes that would be the calculate a new position in that direction from the origin position approach
i've been trying to limit the speed of my rigidbody controller but it doesn't seem to work
these two functions get called in update one after another (with MovePlayer() being first)
the problem with this is that AddForce doesn't actually apply the velocity change until the physics simulation runs
which happens after FixedUpdate
btw when adding forces you should only be using FixedUpdate
(and should not be using deltaTime either)
i'll give that a shot , thank you
I have another question about good practice. Is it better to create a variable within a loop to minimize scope, or is it better to create a variable outside of a loop to avoid creating a variable every frame?
the Update() loop in this case if that helps
variables should generally be declared in the innermost scope possible
Perfect, thanks!
Premature optimization is the worst practice of them all
hmm.. it still doesn't quite work as intended.. the idea is to be able to change these two values so that move speed handles acceleration , and top speed just limits the speed so that no matter how much i increase move speed , the speed is always at top speed
you'd have to show code
!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.
don't use screenshot
{
moveDirection = transform.forward * verticalInput + transform.right * horizontalInput;
rb.AddForce(moveDirection.normalized * moveSpeed, ForceMode.Force);
}
void SpeedControl()
{
Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
//limit vel if needed
if(flatVel.magnitude > topSpeed)
{
Vector3 limitedVel = flatVel.normalized * topSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
}```
Ask it in another channel like #💻┃unity-talk and attach a screenshot of the material that the leaves are using.
what is your Rigidbody drag set to
5 on ground
also these
public float groundDrag;
public float airDrag;```
that's massive
it should be more like... 0.05
or 0
since you're handling the speed limit thing yourself
setting the drag to 0 still doesn't fix the issue of the player accelerating past top speed
How are you checking that?
Like how do you debug your speed
What do you mean by this? Should I just not worry about FPS or anything until I have finished the game or at least a large portion?
good point , i should probably debug it.
I checked the SpeedControl method and it looks ok
right now i check by just setting the moveSpeed variable(the one that accelerates) to a high number and seeing if i go at lightspeed or if i stay at topSpeed
you know the really weird thing is that it prints out the speed as being exactly the same as top speed , even though i'm clearly going way faster
set the top speed lower
what happens
12 is pretty fast
even if i set the top speed to 0 , it still moves , but it prints out 0
what happens if you set it to 1
Knowing what actually affects performance is very hard, and generally people end up sabotaging their own code by choosing to do something based on imagined performance benefits (like where the variables are declared)
moves but slowly right?
yeah
here
oh i see..
so you're adding the force, printing the velocity. It's still 0
Then the physics sim runs, the force accelerates you
and you move a little for one simulation frame
then your code runs again, etc
so what would be the solution? running SpeedControl() before MovePlayer()?
One way to get around this is manually do the AddForce calculation and set the velocity yourself
instead of calling AddForce
e.g. instead of
rb.AddForce(moveDirection.normalized * moveSpeed, ForceMode.Force);
You do:
rb.velocity += (moveDirection.normalized * moveSpeed * Time.fixedDeltaTime) / rb.mass;```
which is the same calculation
but you'll be able to clamp it effectively
I'm actually currently making an asset store asset to help people with just this problem lol (among other things)
hey it worked, i needed to change some architecture but in the end making EVERYTHING static worked out. so now it works like normal playerprefs, but with binary encryption :)
I don't think Fifa games use a "basic" system
It's probably quite complex
Maybe FIFA 97
Has an achievable level of "basicness"
But these new football (and other sports) games have pretty complex IK + physics based animations stuff
But you could build a simple system with colliders and rigidbodies
it needs only throw the ball to a random spot inside the goal.
im not making fifa
I read it as passing, not shooting for some reason
Just a penalty/free kick?
no shooting during the match
yeah passing, dribbling etc.
So the real question is "how to get a random position in a goal" right?
Since you already have passing
yeah
You can use Random.Range to generate coordinates inside the goal
would anyone know how to convert from array grid to world position and vice versa while having it so that it does the calculations as if the grid's pivot is at the center instead of the bottom left?
@cedar pivot Like
Vector3 targetPos = new Vector3(Random.Range(-goalHalfWidth, goalHalfWidth), ...);
// Convert to world space
targetPos = goalTransform.TransformPoint(targetPos);```
And then get a direction from the ball to the target with:
```cs
Vector3 dir = targetPos - ball.position;```
oh i understand now thanks :)
Use Unity's Grid component, and use the CellToWorld and WorldToCell functions on it.
i am using an array grid using an array inside a job for pathfinding,the thing is that i need to calculate some stuff but it doesn't work correctly so i want some help with that
yes by all means use your array with grid coordinates in your job
then to translate back into unity world space use the Grid component
the thing is that would require moving the grid,and the target position outputted may also not be equal to the grid position
let me explain
public int2 gridSize;
public int2 startPosition;
public int2 endPosition;
public float2 origin;
public float offset;
public NativeList<float2> resultPath;
these are the variables that affect the grid
int2 GetInt2FromVector2(Vector2 position)
{
int x = Mathf.FloorToInt((((position - startPosition).x) / offset) + ((gridSize.x / 2f)));
int y = Mathf.FloorToInt((((position - startPosition).y) / offset) + ((gridSize.y / 2f)));
return new int2(x,y);
}
this converts a position from Vector2 to an int2
private float2 GetPositionFromInt2(int2 value)
{
return (new float2(value + origin) * offset) - ((gridSize.x / 2f) * offset);
}
this gets the int2 value and creates a float2,which will later be converted to a Vector2
Better suited. So what if it’s bad
Help what if Im making a game in unity and I want the character (third person) to play an animation, like turning 360 degrees rq or something, without disrupting any input, such as moving forward relative to the player? Would I have one gameobject as the moving player and a child object as the rendered part?
yes
i really need help. so my goal, i have 9 "trees" in my scene. and a collection point. i want to find the closest tree relative to the collection point. BUT. it finds the 2 clostest, that works. but then it goes to the one that is clearly farther away. i dont understand any of it. please can you help...
public IEnumerator Tree()
{
if (AutoFarming)
{
foreach (Transform tree in Trees)
{
float dist2 = Vector2.Distance(tree.position, CollectionPoint.transform.position);
Debug.Log(dist2 + "--" + tree.name);
if (dist2 < nearestTreeDistance)
{
//Debug.Log("Found new clostest" + dist2);
nearestTreeDistance = dist2;
if(tree.GetComponent<Tree>().IsCut == false)
{
nearestTree = tree.gameObject;
//Debug.Log("Found new clostest NOT CUT");
}
}
}
//Debug.Log("Searching completed");
if(nearestTree != null)
{
Debug.Log(nearestTree.transform.position + "---" + CollectionPoint.transform.position);
Clicked = nearestTree.gameObject.transform;
nearestTreeDistance = float.MaxValue;
nearestTree = null;
Completed = false;
walkfunction();
}
else
{
yield return new WaitForSeconds(2);
// Debug.Log("Didnt find, called again");
nearestTreeDistance = float.MaxValue;
nearestTree = null;
//StartCoroutine(Tree());
}
}
}
by the way, when it finds a new nearest the caracter walks to it (automatically, see the walkfunction being called) and cuts it down. ( and setting the spriterenderer to not visable)
for refference, dots are trees
you'd n eed to share more context here
like where and when you start this coroutine
yeah... why are you doing that there
that should just be basically the first statement in the coroutine
also that variable should be local
so it can't be messed with from outside
As should nearestTree
also the grid position works via Vector2Int, so i would need to convert that to int2,which would be a lot of work,as such i think just calculating them correctly would solve the problem
int2 and Vector2Int can be implicitly converted
ok i did what you said, nothing changed
YOu should also provide the other information I asked for please
basically - providing the whole script would help
yeah,but i would still need to convert my entire system to work with the grid component,and i don't think that would be easy,what's wrong with telling me the correct calculations?
i start it when i press the upgrade button for Auto tree farming. then it sets the "AutoFarming" to true and starts it
330 lines, you want it all?
📃 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.
its a gamemanager script, so it does al sorts of stuff
(function is not called from that script tho)
public void AutoTree(int cost)
{
if (GameManagerScript.Money >= cost)
{
GameManagerScript.Money -= cost;
GameManagerScript.AutoFarming= true;
StartCoroutine(GameManagerScript.Tree());
}
}
this is what calls it (a button calls the AutoTree function)
it's definitely doing way too many different things btw
should split it into several scripts
you're also doing a ton of reaching into other objects and playing with their internal states, not good practice
oh, ok. idk how else i wuild do it but alr
you make almost everything private
except a few functions which do what you need to do. Those can be public
Like instead of this:
GameManagerScript.Money -= cost;
GameManagerScript.AutoFarming= true;
StartCoroutine(GameManagerScript.Tree());
It owuld ideally be:
GameManagerScript.BeginFarming();```
and GameManager would do all that stuff internally
Hello! I started working with unity some days ago. Im creating a 2d topdown game. I've been trying to figure out why my shooting script won't work correctly (bullets won't follow the cursor location while shooting on the 3rd and 4th quadrant from a starting position) any ideas? let me know if I need to attach the code and/or a video example
it would help to see what the actual behavior you're seeing here is
yeah, i just didnt do that cus its already many functions. dont want to add one for all. (i have like 6 upgrade buttons)
and to knopw what "collection point" is
you are slowly digging yourself into a spaghetti mess that's all
it will grow harder over time to maintain this
but that's ok, we all have to make mistakes to learn
cuild you come call? i will show you behaviour
Make a video, I can't do calls
ok
showing your code and a video would be good yes.
i know how it works, its fine. for me
for now 😉 . Till your girlfriend breaks up with you and you go on a month long wilderness journey to "find yourself". Then you come back and try to work on your game and you go 😵💫
you want the bullet follow the cursor position or you want it to go with the direction that player looking at ?
cursor position
ahhha no, i organised it in a way i can easaly find it back
Suspiciously specific...
maybe one or more of those trees isn't in the tree list
or maybe IsCut is true for it
Also what does walkfunction(); do
Most of the code has been collected from internet though
public class Shooting : MonoBehaviour
{
public GameObject bullet;
public Transform firePoint;
public float bulletSpeed;
public float shootCooldown;
public bool canFire;
private float timer;
Vector3 lookDir;
Vector3 absDir;
float lookAngle;
// Update is called once per frame
void Update()
{
lookDir = Camera.main.ScreenToWorldPoint(Input.mousePosition);// - playerPos;
lookDir = lookDir - transform.localPosition;
lookAngle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg;
//absDir.Normalize();
transform.rotation = Quaternion.Euler(0, 0, lookAngle);
if (!canFire) {
timer += Time.deltaTime;
if (timer > shootCooldown) {
canFire = true;
timer = 0;
}
}
if (Input.GetMouseButtonDown(0) && canFire)
{
canFire = false;
Shoot();
}
}
void Shoot()
{
lookDir.Normalize();
GameObject bulletClone = Instantiate(bullet, firePoint.position, transform.rotation);
bulletClone.GetComponent<Rigidbody2D>().velocity = firePoint.right * bulletSpeed;
}
}
it makes the little guy walk to the desination. then checks where is is and does what it needs to do next
I made a version that works in java (usign libgdx) but it makes the camera unproject
Can you show it
?
the code
its in the pastebin?
xD
Invoke("walkfunction", 0.01f * Time.deltaTime); 😬
that basically just means "wait one frame"
AHHAH
it's not going to wait for that tiny amount of time accurately
oh ok. il change later
Also you're doing this:
Debug.Log("Shuild start new search");
StartCoroutine(Tree());```
And then still invoking walkfunction agaain...
this is just... very hard to follow the logic
and i feel you're going to end up with multiple coroutines and walkfunction invokes running simultaneously
@leaden ice so any ideas on how to solve that problem with math instead of unity components?
yeah, so when it is at a tree, it goes to find the next.
i checked it already, works as expected. (debug log at beginning of em all) they call in the right order
ok just a sec.
heres a video
Several potential problems here:
1: lookDir - transform.localPosition; you're using localPosition instead of world position
2:
GameObject bulletClone = Instantiate(bullet, firePoint.position, transform.rotation);
bulletClone.GetComponent<Rigidbody2D>().velocity = firePoint.right * bulletSpeed;```
using firePoint.right instead of transform.right
tbh I'm not sure I understood what the problem is. What results are you actually seeing vs what you expect/want
i thougt you want the bullet to follow the mouse position 🤣
do you have any idea what my problem is? if no, ill try to ask someone else.
Oh sorry, that was my bad
nvm man
had more ideas above... #archived-code-general message
Okay fixed both potencial problems but it seems to have the same output
all checked. not the case
what object has this script on it
basically,i want to be able to click a point and then be able to that point using pathfinding,but the thing is it keeps moving in weird directions
i don't get what this movement has to do with clicking on points etc
it supposed to move from the starting position to the target position(the clicked point)
very hard to tell where and when you might be clicking in the video
I was expecting you to click on that grid
you can see when i click stuff shows up on the console
that's just to help with something else
ill find someone else.
so how are we going from clicking somewhere, to this code, to something moving?
there's a lot of unknowns here
lots of places where things might go wrong
do you need the pathfinding script?
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.
here it is
wait
lemme edit it,that is kinda old
guys i have an top down shooter game i want the player rotate with the
Mouse X and Mouse Y axis , not facing the cursor .
transform.Rotate
(0, (Input.GetAxis("Mouse Y") +Input.GetAxis("Mouse X") )* 10 , 0);
;
but its not working good at all direction for example Mouse X is going opposite direction if the player is facing left side and the Mouse Y same problem 🥲
@leaden ice now it is fixed,you can check it out
3D or 2D?,cuz that isn't how you do either
its 3d for now 😅
I think I might have found a "parcial" solution. Changing the Body type (of the bullet) from Dynamic to Kinematic makes the bullet shoot in the correct direction. Although it wont collide with objects. Any idea how to enable collision detection with a kinetic body?
ok the problem is obvious then
your bullet is colliding with something right after you fire it
knocking it off course
for example the player himself
the fix is to make the bullet not collide with the player for example, or whatever it is colliding with.
https://www.youtube.com/watch?v=AOVCKEJE6A8 this should help
In this video, I will show you how to aim in an 3D top-down game with the mouse.
Copy the script from here:
https://github.com/BarthaSzabolcs/Tutorial-IsometricAiming/blob/main/Assets/Scripts/Simple - CopyThis/IsometricAiming.cs
Full project:
https://github.com/BarthaSzabolcs/Tutorial-IsometricAiming
The dummy is from Mixamo, named "Manne...
i didn't find any answer for that in the internet , but this code almost worked for me
thanks a lot man
Omg that was it! Thank you so much, I couldnt even notice it. Is there a way I can make them both overlap without having collision problems?
use layer based collisions
or use Physics2D.IgnoreCollision when you spawn the bullet
Okay I will google it
@leaden ice did you find anything worth of interest?
ok. i really cant figure it out. can someone please come call with me?
lines 15 and 196 are probably the only ones you need to look at
.
its should work , i didnt understand your question when you debug the tree name is giving you the nearest tree and after that its goes to the farther ?
Skip cut tree first before you assign nearestTreeDistance.
You're overwriting distance with invalid tree.
i have disconnected my walking function and my cuttree from it now.
i am starting to feel like unity is acting wrongly here
What?
cuz it just doesnt work. it does everything, it checks all trees distances.. and still doesnt activate the if(dist2 < nearestTreeDistance)
You have this line:
if (dist2 < nearestTreeDistance)
{
nearestTreeDistance = dist2;
if(tree.GetComponent<Tree>().IsCut == false)
{
nearestTree = tree.gameObject;
}
}
Which overwrites distance with already cut tree
but that wuildnt matter tho? right
Change it to at least this:
if (dist2 < nearestTreeDistance && tree.GetComponent<Tree>().IsCut == false)
{
nearestTreeDistance = dist2;
nearestTree = tree.gameObject;
}
ok.
I'm spoonfeeding because I gotta go
It matters if you think carefully.
Your tree list is this:
dist: 8, uncut
dist: 4, cut
dist: 6, uncut
Your dist 6 element never get picked because dist 4 cut tree always overwrites nearest distance to 4
Alright, good luck now
can someone call me and help with a simple script rq
Not now this discord works. Ask your question with relevant details and anyone who can and wants to, will help.
my collision script is not working
And ... ?
send it here for people to see
also this should go to #💻┃code-beginner
all the trees have rigid bodies and are on the Mats tag
what is this script attached to? a material? a player?
Hello Guys got a problem why icant apply to a prefab??? even in prefab i cant uncheck the checkbox , in prefab its all gray why?
the sword
Hi guys! I have a really big project, and i'm finding moving large folders to other folders taking a long time (5 minutes+). Is this normal? And what can I do to fix this if anything?
Hello
have you tried to log at the start of your collision function?
I have a problem with materials in scenes for rendering in server Mirror.
does the sword have isTrigger ticked?
yeah it didnt log the collision
either you're not hitting OnCollisionEnter, or your tags are wrong, or IsAttacking is always false
Is this script attached to a GO that has a collider on it
yeah a box collider
I make changes in material of player according with your tag in game and this changes not show for other player in server.
Somebody help-me?
Hi, how I would be able to convert this to unity's new input system?
public Key key;
void Update() {
if (Keyboard.current[key].isPressed) {
// do stuff
}
}```
not that this is a good way to do it in the new system, but this is more or less a direct conversion
tysm life saver
ok do you mind showing me how to do it the better way
there are many ways to do it
#🖱️┃input-system is the place to discuss them
also I don't have much time rn
ok fe thank you
Hello! i want to make system that if you enter in world name field name like buy it creates new world aka scene with name buy
Anyone experienced moving large folders over inside a project taking a long time (5 minutes+). Project is over 30GB+, and using Plastic SCM, so maybe Plastic is indexing things? Or just normal thing?
Have you appropriately ignored your Library folder and all other unecessary folders in Plastic?
For Plastic SCM?
yes
Hmmm, maybe I didn't. Good lead
Learn how to exclude Unity directories and files from your repository, so they are not tracked by Plastic SCM.
Thank you!
couldn't u just do something like
Scene newScene = SceneManager.CreateScene(stringFromInputField);
and get the string from the input field or smthing
Somebody???
Unless you are syncing something over the network, other players will not see changes you make locally
Hmmm, wish I could help @noble leaf but haven't worked with Mirror in a while
Do you know what level to place the conf? On the level of the Assets folder?
I will try this
What's mean conf?
I think yes
I was using git before, so the conf was there, perhaps updating to the specific plastic scm ignore conf will work
Hmmm, updated conf, and still getting this:
Will investigate that link next
so likely i have to disable "move calculation"
are there downsides to disabling move calculation, and should i just reenable when i'm done moving folders?
these are the options:
not sure what to do here
can i just disable "find moved and renamed files and directories", while I'm doing a major project revamp by reorganizing folders, and once i'm done just turn this back on?
(currently moving a folder is taking 10 minutes)
there is a veeery extensive, entire section on the docs for migrating to the new input system
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/Migration.html#unityengineinputgetkeyhttpsdocsunity3dcomscriptreferenceinputgetkeyhtml
cheers i will give that a read 👀
I'm trying to make code such that I can make a dropdown to allow users to change the background image which is just a texture for a quad. Basically, if they choose "beach," the texture of the quad uses the beach .jpg file. If they choose "park," it changes to a picture of a park, etc.
How do I go about coding this? I already made a script but I'm not sure how to change an object's texture properly. I already tried the sample code from this one and all it did was give my quad the same "shadowy texture" as Unity's 3D background space: https://docs.unity3d.com/ScriptReference/Material.SetTexture.html
You will need the instance of matterial for the object you are switching textures on. Then you can use the fallowing. https://docs.unity3d.com/ScriptReference/Material.SetTexture.html
You should also check the shader the texture is using to make sure the variable name matches for what SetTexture uses
"Common texture names used by Unity's builtin shaders:
"_MainTex" is the main diffuse texture. This can also be accessed via mainTexture property."
to find that out go to the material and in it's options hit show shader
'"shadowy texture" as Unity's 3D background space:' not sure what that looks like, but probably is that your shader uses a different variable name.
I'm sorry, I'm still a beginner and not quite sure how to do this.
Go to your material on the object, and right click the header, there should be a select shader option
Or getting the material? You should just be able to make a variable on your script of type Material, and then drag and drop it.
So I'll momentarily write my code and paste it here and maybe you can see what's going wrong. I'm only trying to change the Albedo texture, basically.
public class BackgroundChange : MonoBehaviour
{
//Set these Textures in the Inspector
public Texture m_MainTexture, m_Normal, m_Metal;
Renderer m_Renderer;
// Use this for initialization
void Start()
{
//Fetch the Renderer from the GameObject
m_Renderer = GetComponent<Renderer>();
//Make sure to enable the Keywords
//m_Renderer.material.EnableKeyword("_NORMALMAP");
//m_Renderer.material.EnableKeyword("_METALLICGLOSSMAP");
//Set the Texture you assign in the Inspector as the main texture (Or Albedo)
m_Renderer.material.SetTexture("bg_apartment", m_MainTexture);
//Set the Normal map using the Texture you assign in the Inspector
//m_Renderer.material.SetTexture("_BumpMap", m_Normal);
//Set the Metallic Texture as a Texture you assign in the Inspector
//m_Renderer.material.SetTexture("_MetallicGlossMap", m_Metal);
}
}
So that's what I have written down, right?
I assume I don't need to access the normal and metallic stuff
so i commented those out
ah you have c++ background I see.
C# :P
also the code snippet is just a copy/paste from the documentation actually
so that looks good, just switch "bg_apartment" for "_MainTex"
and bg_apartment is just meant to be that file
you will just assign that file to the m_MainTexture variable in the editor
the first argument is for what variable on the material you are setting, and the second argument is what texture to use.
Oh, so like it would be "_MainTex", bg_apartment?
yep. Like wise the second argument can be any of those textures you want.
Also the m_ variable naming convention is c++ for private varaibles so switch.
to
public Texture MainTexture, Normal, Metal;```
like wise you might see it for private variables in C# but ussually it is just c++ programers sticking to what they know, and just _ is more common in C#.
also doing this gives me an error
and gotcha, i switched it
m_Renderer.material.SetTexture("_MainText", MainTexture);
The name of the texture file you want isn't important here, once this script is on your object you will be able to assign it in the editor to the texture variable.
don't know if that's important for anything in this context
ah, hm
what if i want to do it via dropdown?
as in, a user selects "Apartment" and it'll switch the quad's background/texture to bg_apartment.jpg
Do you want the user in game, or user in editor to be able to select it?
user in game
it's meant to be via a UI element
"select a background" up top there
ah, interesting. now the background went default
Is the BackgroundChange script on that drop down or on the background itself?
the background itself
I imagine it is starting on the new background instead of a grey one?
nope, it's a grey one
Update: turning off find moved and renamed files seem to have fixed the issue!
not quite sure i understand what you mean, sorry
Your screen shots shows it is. So the Background Change component has 3 public variables, MainTexture, Normal, and Metal. Those are showing up in the editor, and bg_apartment is assigned to Main Texture
well i just manually assigned it for the sake of the screenshot ^^
it's actually set to None as well by default
ahhh i se
see
Ah so if it is none when you play the game and then assign it, it won't be changed as the assignment is happening in the Start() method, which is only ran once.
i set it to bg_apartment after i turned on game mode
right
changing it to that before does count though
so i believe i set it in the update() method then, not start()
For now we are just testing, so either works.
Okay, I went ahead and switched it to Update() just because that's likely what i'll use later anyway.
Also I can confirm that with Update(), manually changing it via editor while in-game did work
What we will want to actually do is make a new method with three parameter's (one for each Texture).
yes
here's the updated code
public class BackgroundChange : MonoBehaviour
{
//Set these Textures in the Inspector
public Texture MainTexture;
Renderer m_Renderer;
// Use this for initialization
void Update()
{
//Fetch the Renderer from the GameObject
m_Renderer = GetComponent<Renderer>();
//Set the Texture you assign in the Inspector as the main texture (Or Albedo)
m_Renderer.material.SetTexture("_MainTex", MainTexture);
}
}
So doing it on update does allow you to change the texture, but isn't how it should be done for this since you want the drop down to change the background, and since Update is called each frame so we would be getting the renderer each frame as well. What we want is someway for the dropdown to hook into our BackgroundChange script. So replace the Update() with the fallowing.
public void Start(){
m_Renderer = GetComponent<Renderer>();
}
public void AssignTextures(Texture Main){
MainTexture = Main;
m_Renderer.material.SetTexture("_MainTex", MainTexture);
}
Edited*
What this does is gets the Renderer when the game starts, and allows outside scripts to assign a new texture.
interesting, i'll note that down
also, for another dropdown i used (the one for shape you see in this screenshot), i used a switch statement in my update method and a method at the bottom of my script:
public void changeShape(int tempShape)
{
shape = tempShape;
}
and then for that dropdown, i attached the script and it detected this method ^
and all it does is allow users to select one of unity's default shapes (sphere, cube, cyllinder, capsule) and then shoot a ray to spawn them
so i was wondering if something similar could be done here
i did copy down this code, though ^^
just in case this is a better approach
The main reason not to do it like that is performance, and clarity. Something like assigning the texture only needs to happen once when the texture needs to be changed, but in update it would be happening everyframe. Though if it is working for you and performance is fine so far I wouldn't worry about it(as long as the functionality is working it is fine).
yeah, it's functionally working fine right now
also if i don't put it in the update() method, how will it detect that the user wants to change backgrounds via the dropdown?
Next you will just need to hook the value changed event on the dropdown to this script(or a script with a texture that then sends that script to this script).
Ah, someone mentioned events yesterday but I don't think I've ever used events before
The value changed event will happen when ever the user makes a new selection. If that event is hooked into the AssignTextures() method it will happen every time it changes.
One of the more advanced type of Unity Menu tools - However, you'll definitely want to know how to use it for many game settings! Learn everything you need to create an easy powerful dropdown UI in the next 2 minutes :)
If you enjoyed this video, I have a small 1$ Member perk available for anyone who would like to help us save up for Facial Mot...
They go over how to hook into the events, though you will need to modify it for texture changing vs color changing.
okay, i'll take a look and give it a try. will report back shortly with results/questions. thank you. 🙂
Also note with this way vs update, this will only work in game, though there is a change I can do if you want it to work in editor also.
oh it's fine, i only want it to work in game
@fluid lily So halfway through, he drags his "panel" onto his "My Image", but I don't know what I'd drag onto what in this situation.
So first, let me go ahead and provide the code I made related to this video
public class BackgroundChange : MonoBehaviour
{
//Set these Textures in the Inspector
public Texture MainTexture;
Renderer m_Renderer;
public Dropdown dropdown;
// Use this for initialization
public void Start()
{
m_Renderer = GetComponent<Renderer>();
}
public void AssignTextures(Texture Main)
{
MainTexture = Main;
if (dropdown.value == 0)
{
m_Renderer.material.SetTexture("_MainTex", MainTexture);
} else if (dropdown.value == 1)
{
m_Renderer.material.SetTexture("_MainTex", MainTexture);
} else if (dropdown.value == 2)
{
m_Renderer.material.SetTexture("_MainTex", MainTexture);
} else if (dropdown.value == 3)
{
m_Renderer.material.SetTexture("_MainTex", MainTexture);
} else if (dropdown.value == 4)
{
m_Renderer.material.SetTexture("_MainTex", MainTexture);
} else if (dropdown.value == 5)
{
m_Renderer.material.SetTexture("_MainTex", MainTexture);
} else if (dropdown.value == 6)
{
m_Renderer.material.SetTexture("_MainTex", MainTexture);
}
}
}
i kinda did the same thing as the guy in the video
but i also can't tell what he dragged onto what around halfway through the video to connect it
why are all of your if statements doing the exact same thing? what's the purpose of the if statements?
okay so this is the goal of what i'm trying to do right here
and i'm relatively new to coding so still trying to understand what in the world i'm doing
well not new but just inexperienced i guess
so i'm trying to do something very similar to what this guy is doing in the video
store the textures you want to assign into an array, then you could use the dropdown.value to access an index of the array
except instead of changing the 'background colors,' it's the texture of the quad
then you won't need all those if statements and your code gets shrunk down to like 2 lines at most instead of however many that is for all those if/else if
if you assign all of the textures in the array in the inspector then you can even just use code in Awake or Start to change the dropdown values to match the array so that you don't have to manage those manually
i also need help figuring out where to drag and drop the script/quad
rn i'm just feeling rather confused
here, i can take a screenshot of what i'm looking at
so background is the quad in the background, ofc
Dropdown - Background is what I want to use for what i'm doing
similar to what video person did
and BackgroundChange is the script i'm trying to use
the one above
right now the script is attached to Background
and i tried to put "Background" on my "Dropdown - Background" to access the AssignTextures method
and my goal is to access the first 6 files you see at the bottom there
via the dropdown
your BackgroundChange component currently searches its own gameObject for a Renderer to change the texture on, if you want to get the renderer from a separate object then you need to stop using GetComponent<Renderer> and instead just use a serialized field and drag the correct renderer object into that.
then you also need to make an array of Texture like i mentioned above so that you can put all of the different textures into that array for the reason i stated above
so i drag Background onto Dropdown - Background still?
that's what I have on the dropdown right now
So we will just want to modify the original script a bit.
For the MainMaterial variable we will want an array(multiple Textures). To do so make it as fallows.
public Texture[] Textures;
Then we will want the instance of the drop down like he did in the video, so the variable he had in his script. the myDrop.
Then in the AssignTexture method, change it so there are no perameters so just ().
and instead of having to do all the if statements just have one line as fallows.
m_Renderer.material.SetTexture("_MainTex", Textures[myDrop.value]);
perfect. Now in the drop down component call that method.
Note that the script is still attached to the quad 'Background'
And Background is what I dragged onto the dropdown
is this correct?
Also in the editor in the new Texture array variable, you will have to assign all the texture in the order of your drop down.
That looks good.
You mean under Background?
because this is what i see
So assign a value of 7 to size
the first one you will leave empty, and then second one assign the Apartment Texture, third one assing the Beach texture, ect.
Right, so I got to this:
And I tried running to see if the dropdown would change anything and it doesn't
This is just basicly a grocery list of Textures in the order of your dropdown. The assignTexture method will assign the texture with the associated place in this grocery list of textures to your background.
Also i ran into an interesting issue: When I open the dropdown and select something, I have to click twice on an option for it to select. Otherwise it puts a checkmark next to every other option I select.
That is indeed weird, is the is the functionality working though?
In the AssignTexture method do a debug.Log for the dropDown.value
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BackgroundChange : MonoBehaviour
{
//Set these Textures in the Inspector
public Texture MainTexture;
Renderer m_Renderer;
public Dropdown dropdown;
public Texture[] Textures;
// Use this for initialization
public void Start()
{
m_Renderer = GetComponent<Renderer>();
}
public void AssignTextures()
{
m_Renderer.material.SetTexture("_MainTex", Textures[dropdown.value]);
}
}
alright
This will let us know if it is atleast being called.
and right now, line 23 is just my debug line inside AssignTextures()
i put it above the m_renderer line
oh and i showcase the dropdown issue i'm experiencing here ^^
Ah yeah if you moved the background script to the dropdown you will need to manually assign it.
Just make it public and get rid of the start() call. Then in editor assign the background renderer.
I have no clue what is happening for the dropdown, but if it is throwing an error I can help.
So make m_Renderer public and get rid of start() and everything in it basically?
Yes. You will manually assign it. The GetComponent like box was saying only works if the script is on the object that has the component.
Okay, I'll try that out in a minute. Also, if anything, I could try and make a fresh new dropdown instead.
True, probalby it is from grabbing that renderer from the dropdown.
okay, here's the new script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BackgroundChange : MonoBehaviour
{
//Set these Textures in the Inspector
public Texture MainTexture;
public Renderer m_Renderer;
public Dropdown dropdown;
public Texture[] Textures;
// Use this for initialization
public void AssignTextures()
{
Debug.Log(dropdown.value);
m_Renderer.material.SetTexture("_MainTex", Textures[dropdown.value]);
}
}
and I went ahead and made a completely fresh dropdown
no objects attached to it right now
@fluid lily okay, here's the update: dropdown is now fixed in the sense that it doesn't have that weird bug
but it also won't change the background still?
i went ahead and attached background as a renderer
This is the inspector view for Background
i believe i did this
but yeah, the texture is still not changing i think
you need to either pass the index from the dropdown or actually get a reference to the dropdown
in the screenshot above you clearly do not have a reference to the dropdown
so i dragged the dropdown - background onto it
it still doesn't work though
define "doesn't work"
so i changed the value here
and it didn't change the background
any errors in the console? have you set up the dropwdown correctly?
no errors in the console
as for dropdown, i'm not 100% sure if i have it set up correctly
here's what i got so far for the dropdown
do i have to drag something onto the on value changed here? is it background itself?
you have to drag the object that has the method you want to call when the value is changed
To the script we're working on is currently attached to the quad Background. Does this mean I drag Background onto Dropdown - Background?
obviously yes
sorry man, it wasn't obvious to me [still new to all this stuff]
but hey
i got it working finally
so thank you for the help
perhaps #💻┃code-beginner would have been a better place to ask your question then
I did earlier but no responses at the time because the helpers were focused on other questions. I did make sure to post there first, though. 
How would I be able to change the rotation of a game object relative to another game object's rotation? I'm trying to get it so a game object attached to my player will rotate relative to the platform the player is standing on, but I can't figure out how.
what causes it to rotate?
I'm not exactly sure. The moving platform is an add-on and I haven't looked into that.
not the platform
you said you want to change the rotation of some object relative to the platform
what effects this "change"
some input?
You press A and it rotates?
What?
The platform's rotation would change the rotation of the object attached to the player, not any input.
so you just want the object's rotation to match the platform's rotation?
No, I want the game object's rotation to be relative to the platform's rotation.
what does this mean then
I don't understand
draw a picture perhaps?
how do I run an argument on the macOS Terminal in Unity?
for windows putting /C in front works but for mac it doesn't
huh
example?
If the player's rotation (on Y axis) would be 90, and the platform's would be 0, if the platform rotated to 90 then the player's would change to 180. If I set the rotation of the player to the platform's, both would be the same, which I don't want.
save the diff when you land on the platform
then apply it frame by frame?
Quaternion diff;
Transform platform;
void OnTouchPlatform(Transform thePlatform) {
platform = thePlatform;
diff = transform.rotation * Quaternion.Inverse(platform.rotation);
}
void LateUpdate() {
transform.rotation = platform.rotation * diff;
}```
Or... just parent it
oh so for windows my code is
System.Diagnostics.Process.Start("CMD.exe", $"/C python3 -c \"import sys; sys.path.append(r'{assetPath}\\Scripts'); import main; main.main()\"");
or use a RotationConstraint
and then for mac it's
System.Diagnostics.Process.Start("/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal", $"-c \'python3 -c \"import sys; sys.path.append(r'{assetPath}\\Scripts'); import main; main.main()\"\'");
why are you running a terminal to launch python
well I made some changes to try to get it to work but /c
why don't you just launch python directly
because it works fine as it is
ok but you're jumping through extra hoops and now running into this problem where the two shell applications require different syntaxes
if you just run python directly you won't need to do that
oh so I launch python itself?
yes
that doesn't work either
do you know just the best way to execute commands in the terminal through c#? that thing works when I copy paste the argument into terminal directly
I just need to know how to make it get in there automatically
Is there some type of tool or plugin i can use to auto fill and easily reference the docs?
Like hovering over a method to see what it does
Yes when your IDE is configured properly it will work this way
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
how's this? I have no idea what I'm doing but this seems like it should work
ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/Python3";
proc.Arguments = $"import sys; sys.path.append(r'{assetPath}\\Scripts'); import main; main.main()";
Process.Start(proc);
looks like you are trying to provide the python program as command line arguments? It should be passed in either to stdin or as a .py file referenced in an argument
oh so if I just link it main.py by itself it should just work?
I mean if I call main() at the end of main.py
oh it's the script I'm trying to run
and I guess I need to show it the path right
I have Intellisense and everything, that's not exactly what i was looking for tho
I did everything in the linked wiki
I was just hoping for a bit more info than what's supplied here
More than that you'll find in the actual docs.
I'm trying to have an event invoked when a value is changed. I know I can do this simply with properties, but I also want these events executed on inspector change. Is OnValidate method the best way to do this?
that'll really be the only way to detect if something has been changed in the inspector, yeah. but it's not really advised to do much work from OnValidate (besides validating data applied via the inspector)
That's all I need it for, along with the event invoke.
I was just hoping to avoid having to store a second variable.
Hey guys! I'm having a bit of a problem. In my game, gravity (and all player Y-movement) is decided via a variable we'll call velY
This is changed base on what the player does. When the player jumps, velY is set to a predetermined positive "jump" value which is then lowered by a constant gravity variable.
All adjustments to the velY variable are done without using Time.deltaTime, but the actual movement itself IS dictated by Time.deltaTime. Here's a small example of what I mean (leaving some things out to avoid bloating):
update()
{
if([not grounded])
{
velY -= [gravity variable];
}
if([jump button is pressed])
{
velY = [jump force variable];
}
characterController.Move(velY * Vector3.up * Time.deltaTime);
}
This worked just fine during the testing process, but when I built the game and tested it out as a separate application, the gravity was significantly more floaty than usual, with jumps reaching tremendous heights and falling down very slowly. What am I doing wrong here? Theoretically since the gravity isn't affected by the deltaTime, it shouldn't be lowering any lower than in the Unity tester, right?
you should show your actual code as well as the values of the variables you are using. there's no way to know what your calculations will end up like without that kind of info
also gravity is an acceleration, you would typically multiply it by deltaTime twice because of that (first time to calculate how much velocity to decrease Y by, then again when you actually apply it in the Move call)
Yeah sorry about that. I took a little bit too long to test my game outside of the unity tester, so it would just be too difficult to post all of my code here now. I do see what you're saying though. Would that mean I, using the example above, change:
velY -= [gravity variable];
to
velY -= [gravity variable] * Time.deltaTime;
?
that's typically what you would do, yes. if your gravity variable is 9.81 (or just not already multiplied by deltaTime)
Nah it's not. I'm trying to make a homage to ps1-style collectathon/adventure games, so I've been trying to emulate some of their physics, like a bit lower gravity and high jumps. Thank you for the advice! I appreciate it
do note that if your gravity was floaty without that multiplication then it will likely be even worse with it because the effects are now even more reduced
I'm testing it out now, and adjusting the gravity variable (and other such variables) to try and find something that suits my interest
It worked! Thank you so much again! Now to go apply that same concept to my other acceleration variables
Do you think the same would apply to variables controlling deceleration?
Something like:
Mathf.MoveTowards(variableA, 0.0f, decelA) -> Mathf.MoveTowards(variableA, 0.0f, decelA * Time.deltaTime)
you most likely would want to multiply your decelA variably by deltaTime in that instance, yes because MoveTowards would be probably called every frame and that third parameter is the speed it should move per frame (or rather per call)
Rad. I tested it out and it seems to all be working pretty well 👌
Vector2 randomFactor = UnityEngine.Random.insideUnitCircle * player.CurrentWeapon.WepData.BaseInaccuracy * player.CurrentWeapon.HipfireStanceMult;
shootRay = player.Look.playerCamera.ViewportPointToRay(new Vector2(0.5f, 0.5f) * randomFactor);```
I'm trying to get a random point in a circle on the screen
is this the way of doing it?
well does it work?
I got no idea on how to debug it
I'll try visualizing the raycast
but the origin is coming from the screen so
You can have debug rays linger for a second
I'd assume that adding the vectors in the second line would be correct instead of multiplying
you can also just log the value and see if the numbers are in the correct range
Debug.DrawRay(shootRay.origin, shootRay.direction, Color.red, 99f);
``` well I don't see anything with this
OH WAIT
it's only on scene view
but I need to see my game view
make sure you have gizmos enabled in game view
And since it's direction, which is probably normalized, you might want to multiply that value by something to make it more noticable
alright I'm can see the ray now, the ray is going downwards while looking at front for some reason
randomizing is causing it
nvm ignore that question i asked, it was dumb
trying to raycast inside an imaginary circle bordered by the crosshair
Did you already do these?
doing it now
beautiful, thanks @mellow sigil and everyone else
Unity usually does not supply a lot of information on their methods, fields, classes and properties. You're better off looking up the Unity docs. I don't think there is a plugin that can auto reference the docs (maybe a good idea to create that one day?).
Modulo on negative numbers are weird. But why would this give 35900? -100 isn't bigger then 36000, so why would it subtract anything?
My calculator gives me 35900
I'm simply trying to wrap around the euler range
c# % operator isn't a true modulus, it's a remainder operator
in fixed point format
If the -100 is not a variable: Try with brackets? (Residual) division goes for plus/minus calculations?
That's not going to do anything
honestly just perform the % operation then if the value is < 0 add it to the original number to get it to wrap
int mod = x % y;
int result = mod < 0 ? y + mod : mod;
((a%b)+b) % b works nicely 🙂
actually even better would just be (x+y)%y
(-100 + 36000) % 36000 is 35900
(100 + 36000) % 36000 is 100
ah wait, that likely wouldn't work for negative values below the y value
Yeah was just testing that
honestly the ternary (while probably not ideal) would probably be the best option here since the intention of what it is doing is pretty clear as compared to ((a%b)+b) % b
hey there, after updating from Unity 2021.3.14f1 to 2021.3.18f1 I get NullReferenceException
in unitys unity/unity/Editor/Mono/SceneView/SceneView.cs:3693 at every push of play.
Afterwards the unity editor is frozen, the stack trace doesn't mention any of my code.
Is anyone aware of anything particular that changed in the last versions that could be causing this?
Any tips on how I could zone in on what part of my UI could be causing this?
What is the stacktrace?
Does reloading the project fix it?
Does updating to a newer patch version fix it?
Is it possible to revert back to an earlier version by any chance?
afaik 2021.3.18f1 is the newest unity version
What do you mean exactly by reloading the project? I have deleted the Library folder and reopened the project?
Is it possible to revert back to an earlier version by any chance?
yeah, I have also reverted back to 14f1 now, the GUI error doesn't happen anymore, but it still freezes. It's weird because I didn't open it for 2 months and It worked fine last time I opened it (same 14f1 version of unity)
afaik 2021.3.18f1 is the newest unity version
Ah, I see, then that's not possible.
What do you mean exactly by reloading the project? I have deleted the Library folder and reopened the project?
Yes, regenerating the library folder is always a good idea. I mean reopening the project altogether (closing Unity, opening Unity, loading the project).
The error is indeed something related to Unity internally, and if reloading the project does not fix it, I don't think there is much you can do except for omitting this patch.
One thing you could do in order to fix it is submit a bug report, obviously. You would need to make a minimal example that has this error, which can be difficult to tackle of course. It's completely up to you.
Yes, regenerating the library folder is always a good idea. I mean reopening the project altogether (closing Unity, opening Unity, loading the project).
Yeah, unfortunately I can only press play, unity freeze, kill unity, go to~/Library/Logs/Unityto get the log, read through the raw file log to get info on whats going on.
So I have to restart unity every time I try somethig new anyway
The error is indeed something related to Unity internally, and if reloading the project does not fix it, I don't think there is much you can do except for omitting this patch.
yeah, thats going ot be hard since I don't know what part of my app is causing this (yet)
Hey guys.
can you overlook this piece of code and tell me why it wouldnt work. Am i missing something?
if (Input.GetAxis("Mouse ScrollWheel") > 0) zoomLevel++;
if (Input.GetAxis("Mouse ScrollWheel") < 0) zoomLevel--;
var localPos = Vector3.forward * zoomLevel;
transform.localPosition = localPos;
omg nevermind it does work. I had something else controlling my transform.postition.
Ok my next big issue. How can I move my X & Y axis in global and Z in local?
thank you for your feedback though, it helps enormously to just have someonee to talk to. These problems are always the hardest in unity
You said, it freezes when you hit play only?
actually, I managed to unfreeze it now but updating to the latest version of the Photon network SDKhttps://doc.photonengine.com/fusion/current/getting-started/sdk-download
Global cross platform multiplayer game backend as a service (SaaS, Cloud) for synchronous and asynchronous games and applications. SDKs are available for android, iOS, .NET., Mac OS, Unity 3D, Windows, Unreal Engine, HTML5 and others.
not that any error in the logs would have pointed to that
Usually play mode freeze is caused by some infinite loop. But maybe you already filtered that out
or that you would expect if you change nothing else about the project, the same old sdk from 3 months ago should still work
If its the photon sdk, it might just be a bug that got correcet responses 3 months ago, now they updated something and you get thrown into an infinite loop.
yup, on their server side. At least the actual app running on customers devices still seems to work
Only Photon Devs will know probably 😄
(0.03f * Mathf.Pow(10, 2)) Why does this give me 3
(int)(0.03f * Mathf.Pow(10, 2)) Yet this gives me 2?
The float is literally 3.000000 when I .ToString() it
I don't understand why it's just dropping a whole number when casted to int
help i have a super wierd bug.
unity is claiming that both these transforms are at 0,0,0, while that is obviously not true.
did i change some wierd setting about reference space?
whats going on
both are top level entities.
all right, the spheres child transform with the renderer was offset. but why would it show the childs position as the parents position??
it's not though. The parent is at 0,0 and the child transform shows the local position which would be the offset
so it is correct
select the child and show a picture of that
here is the child:
and here the parent.
notice that the visual arrow indicators are wrong for the parent
oh, i get what you mean now
uh, i think theres a setting somewhere
let me try to find it
thanks it super confusing.
for the spaceship, unity puts the visual indicated position at some random deep nested child, far behind the ship
huh, well the button i thought it was, isnt reproducing your issue
i thought it was the pivot button at the top of the scene bar
im like 150% sure its a recent thing. i didnt have that issue a couple days ago
usually its wrong to cry "its a bug" but this smells a lot like it tbh lol
Are you on pivot mode, set at the top of your scene window?
And if so, then that's where those model's pivots are located.
i have no idea lol
i cant find anything on google, how would i change in/out of pivot mode?
At the top of the scene window is a drop down to toggle between pivot and center mode.
Pivot is almost always the setting you want to be on.
i found it. it was set to "Center"
setting it to pivot fixed it. thanks dude
neither google not chatGPT were at all helpful... thank god this community exists ❤️
https://dotnetfiddle.net/fIjd9T floats are just weird
How can I create my own custom project settings for my package?
Your example is showing the float behaving as expected though
even when I cast to int, it's still 3
Debug.Log((int)myFloat);``` This also gives me 3
yes but in actuality it’s 2.99999
float myFloat = (0.03f * 100f);
Debug.Log((int)myFloat);
This gives me 3.
float myFloat = (0.03f * (int)Mathf.Pow(10, 2));
Debug.Log((int)myFloat);
This gives me 2
It just doesn't make sense
Like I completely understand what floating point errors are
but jesus
this shouldn't happen
if you look at the second print, it shows the “real-er” answer since doubles have 2 times the precision of a float
Because ToString of float does rounding and int cast does truncate
Alright, but why does the power approach give me 2, yet * 100 gives me 3?
They're both floats
I guess the power result probably has some float errors already attached to it
since it needed to be calculated then
that would probably make the most sense
There are no integer Pow and it is implentation detail if they have some optimization for integers. So best to assume there are always floating point error. Also 0.03f * 100f would become just compile time constant fyi.
alright. So like if I'm using this to quantize floats, do I just have to hardcode all of the available precision options in then?
Why not just go with Round?
Speed is everything when you're packing up data for hundreds of users in a maximum of 30 milliseconds
I guess mathf.pow is pretty slow now that I think back on it
Eh, good luck with that, sounds like PO
Pow is not very fast for sure, it’s basically sqrt and more
what do the channels in GetUVs and SetUVs correspond to? Different materials on the mesh? Different UVs maps? (my mesh is from blender) Can't work it out or find an answer I understand online. I'm trying to use texture arrays but can't figure out how to refer to different texture array indexes on same model
Is there a way to convert a string to code? I want to make a coding game where the user can modify the code of the game during the game.
public class CharacterRotate : MonoBehaviour
{
public Player player;
[Serializable]
public struct Bones
{
public Transform Bone;
public Vector2 MaxRange;
}
public Bones[] LookUpOffsets = new Bones[5];
public Vector3[] currentBoneRot = new Vector3[5];
void Update()
{
for (byte i = 0; i < LookUpOffsets.Length; i++)
{
currentBoneRot[i] = LookUpOffsets[i].Bone.localEulerAngles; // Line 22
}
}
void LateUpdate()
{
for (byte i = 0; i < LookUpOffsets.Length; i++)
{
Vector3 extraRot = new Vector3(Mathf.Clamp(player.Look.Rot.y, LookUpOffsets[i].MaxRange.x, LookUpOffsets[i].MaxRange.y), 0f, 0f);
LookUpOffsets[i].Bone.localEulerAngles = currentBoneRot[i] + extraRot; //Line 30
}
}
}```
I got no clue what's going on
It is what it says it is. Put the debug message on the reported line and see how you are trying to access out of bounds index in the array.
it says nothing else
Out of range means you accessing index that doesn't exist
Again, put the debug message and see what is actually being accessed and fix it
I don't know how to do that
It tells you what line the error is on. Place your debug log above the error line to check the index value, that's it . . .
the index reaches to 5 somehow, what the hell
Hi there
does anyone know how to modify a variable of a localized string event from script?
for example in a price text where the currency should be localized
You get a reference to the place where the text is displayed, assuming a Text component or TMP_Text component, and update its text field when the event fires.
thats not what I meant
I'm trying to modify the value of a local variable from a localized string set on the LocalizedStringEvent
that
but I dont know how to access it
ok i figured it out... weird that its not documented anywhere
Any resource on how one would design a game’s code architecture?
typical software architectures from general applications work very well
Any suggestions on article or video lectures?
not really...
No problem will research more about the software architecture thanks
I have a particle system all set up and attached to the i have a OnParticleCollision, so when the enemy touches the PS it loses health, for this i had to set IsTrigger to false on the enemy, but I need IsTrigger to be true. How can i keep it true and for the OnParticleCollision to work?
Does anyone have any knowledge on how to make turrets that stay still work when they are a child of some object and rotated? I have this, and it works but it follows World Space, which is not what I want. I tried a few things but thoose didn't work either
Vector3 targetDir = Target.position- laser[0].HorizontalPart.position;
Quaternion Lrotation = Quaternion.LookRotation(targetDir);
Vector3 rotation = Quaternion.Lerp(laser[0].HorizontalPart.rotation, Lrotation, Time.deltaTime * laser[0].Speed.x).eulerAngles;
laser[0].HorizontalPart.rotation = Quaternion.Euler(0, 0, rotation.z);
gotta change local rotation if you dont want to overwrite the parent ones
I don't think that will work then
the angle calcuations will be messed up then
no it doesn't
You have to do the angle calculations in local space
Any instances of .position can just be changed to .localPosition
A little more work when you're thinking about the variables, but that's the gist
parent rotation overrides child not other way around
This is hurting my brain
what do you mean by setting it to local space
what will that do?
it just makes it work even less
you can get and set in world space no problem. But try starting with a turret that points down +Z
Im confused why would you want to calculate it in local space?
I don't know why I would set that to local
there is some bad advice on here... See if there are any Unity learns. a local rotation is not good if you want to look at a world pos
Maybe im missing something
If you're trying to move a child with the parent, local space is 100% better
let me try to illustrate it in paint
Is it a 2D game?
no
it's 3d
I have a ship that can move and rotate
and it has a laser turret on it
which is supposed to look in the direction of the target
yeah so the laser turret should rotate in world space - but your code does something really odd at end. LookAt is an instant point at
this is the part I'm trying to rotate horizontally
the ball would rotate verticially
I would use LookAt but I don't want it to be instantenous
This doesnt really work if your Z axis is up
Unless if you wanna do some extra quaternion math
Try changing it so that the turret's forward is the Z axis
yes
x not z though, z is twist
x up and down
well that is a bit more complex to do in 2 parts...!
do need local rotation of up/down
if it is a space ship then god help you, if ship on sea/ground-plane it is much easier
it's a space ship
The main reason this doesnt work is because you are using an euler Z angle from a look rotation. I don't think a lookrotation ever uses Z angle
Unless if you give it a different up-vector which you dont
Alright I'm changing the axises so up actually points UP
you need to rotate up and down on local x angle, but calculating the angle would be tough if spaceship can twist around
Can it be freely rotating?
well yes the thing holding the ball could move to any angle but only around Up axis
Yeah if your "up vector" changes (like it would when flying around and spinning in space), you would need to use the second parameter of LookRotation to specify the up axis
Okay but is the blue arrow now pointing behind it
Or are we seeing the back of the turret?
yes it's back
or doesn't really matter
but yeah it's the right way
also the top of the ball is where it would shoot from
...Oh
any moving object is best when modelled to face down +Z axis. This is the standard way of doing things
So this was correctly rotated then 😆
well
I didnt realize it's looking up
the ball was
the base of it and the thing that only rotates horizontally wasn't right
There should be an asset that handles turrets that can rotate and aim and guess target point ahead of a moving target if slower projectile...
Probably is none though
I would probably do this with two Vector3.SignedAngle calculations. On around the turret base's y axis, and another around the ball's x axis.
Used what?
when the angle difference get's close to 0 it starts jumping around
this
it only jumps a few degrees but that will totally throw off aim in space combat
Maybe you did it wrong, who knows
I would try to get it to work with instant rotations first, and after thats done I would add the slerping
Btw use Slerp instead of Lerp with Quaternions, its a bit smoother
alright
yeah well it works as long as I don't rotate the ship
as soon as I roll it for example it just doesn't track it
How did you do it
what?
Cant say much without seeing the code
Vector3 targetDir = Target.position- laser[0].HorizontalPart.position;
Quaternion Lrotation = Quaternion.LookRotation(targetDir);
Debug.DrawRay(laser[0].HorizontalPart.position, targetDir * 10);
Vector3 rotation = Quaternion.Lerp(laser[0].HorizontalPart.localRotation, Lrotation, Time.deltaTime * laser[0].Speed.x).eulerAngles;
laser[0].HorizontalPart.localRotation = Quaternion.Euler(0, rotation.y, 0);
basicially the same
How to format code: !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.
what damn character is that
`
it just ins't on my keyboard
Left of 1 on the qwerty layout
Backtick
It is
Not with nordic keyboard 🤷♂️
Which is qwerty
oh
For now, you can copy this
```
well here is the code
could I juse use lookat at set x and z rotation to zero?
Hi hello goodmorning, i made an watershader and i need buyoancy for it. I have been searching the internet for answers for quite some time now and i cant seem to figure it out. I am using vertex displacement. Any help? thanks.
Anyway I would start with calculating the base turret's Y angle
Vector3 lookDir = targetPos - turret.position;
float angleY = Vector3.SignedAngle(spaceship.transform.forward, lookDir, turretBase.transform.up);```
Then the top turret's X angle
```cs
float angleX = Vector3.SignedAngle(turretBase.transform.forward, lookDir, turretBase.transform.right);```
watershader as in a vertex shader for a water mesh?
and now you want objects to float on top always, or do you want realisic buoyancy so they move up/down with a delay?
(i havent done anything similar, just curious)