#archived-code-general

1 messages · Page 40 of 1

coral hornet
#

for example, using his arms to grab on to walls to pull himself around, or dodging bullets by stumbling out of the way

hexed pecan
#

I haven't used it but theres a new-ish Animation rigging package that could be used for that kinda stuff

coral hornet
#

and for this enemy i want to use an inverse kinematics approach, to let him actually grab on to stuff

coral hornet
hexed pecan
#

I mean you would still have to do a bunch of coding

#

If youre good at trigonometry, roll your own IK

plucky inlet
#

There are some hinge overrides and tutorials about how to do IK in unity I would look into

coral hornet
#

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

wide fiber
#
[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?
mellow sigil
#

Use a for loop

final heron
#

Hi guys, is it necessary to install net. sdk if yes where
should I install it in?

leaden ice
#

!ide

tawny elkBOT
#
💡 IDE Configuration

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.

cerulean wraith
#

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?

rain minnow
#

Is there a delay in the audio?

hexed pecan
#

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

kind wolf
#

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

leaden ice
#

pretty common error

#

if you reload the domain it should go away

#

at least until you do the same thing again

kind wolf
#

but the object holding the events gets reloaded as well?

leaden ice
lyric wadi
#

are the events static?

kind wolf
#

therye unity events on a player input component

leaden ice
#

make sure you removed the listeners

#

for the nonexistent scripts

kind wolf
#

can the events still run even if their player input is deleted?

#

i mean ill try it

leaden ice
#

if you have invalid event listeners configured in the inspector, they will cause errors

kind wolf
#

the events are added at runtime

#

not in the inspector

leaden ice
kind wolf
#

theres no unsubscribe code yet

leaden ice
#

and what are the errors

kind wolf
leaden ice
# kind wolf

show the full stack trace of one of those errors

kind wolf
#

basically every input i have gives a similar error

kind wolf
#

oh well

#

unsubscribing worked

leaden ice
#

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

kind wolf
#

so the actions stick around as long as therye subscribed?

swift falcon
#

Hey can i ask a question here?

#

because i have been stuck on something for a few hours now

swift falcon
#

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.

#
  1. 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

red tendon
#

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

swift falcon
#

i don't really know what that is... soo yeah

#

but i got this with arguments and methods (except data processing)

leaden ice
#

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

red tendon
leaden ice
#

With Rigidbody the physics engine does the velocity stuff for you

#

With CC you will have to do it yourself

frigid sandal
#

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?

red tendon
#

in order to detect if the player is trying to move would i have to read from input directly?

swift falcon
#

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

solar terrace
#

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?

red tendon
#

usually i would have an enum that switches between moving and idle based on charactere velocity

leaden ice
red tendon
#

but that wont work

leaden ice
leaden ice
swift falcon
leaden ice
leaden ice
red tendon
#

it just seems wrong to say if (pressed WASD) accelerate

red tendon
#

idk feels hacky

leaden ice
#

isn't that exactly what you want?

#

"If player pressed button, do thing"

swift falcon
leaden ice
#

what's hacky about that

red tendon
#

nothing i guess

leaden ice
red tendon
#

sorry if i came off as a little bit racist btw, i appreciate your help

swift falcon
red tendon
#

i will see how it goes

solar terrace
leaden ice
#

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

solar terrace
#

I fixed it by making the second field position + forward

leaden ice
#

yes that would be the calculate a new position in that direction from the origin position approach

swift falcon
#

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)

leaden ice
#

which happens after FixedUpdate

#

btw when adding forces you should only be using FixedUpdate

#

(and should not be using deltaTime either)

swift falcon
#

i'll give that a shot , thank you

tiny delta
#

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

leaden ice
tiny delta
#

Perfect, thanks!

mellow sigil
#

Premature optimization is the worst practice of them all

swift falcon
#

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

tawny elkBOT
#
Posting 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.

leaden ice
#

don't use screenshot

swift falcon
#
    {

        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);

        }

    }```
leaden ice
#

share the whole script though

#

use a paste site

hexed pecan
leaden ice
swift falcon
#

5 on ground

leaden ice
#

also these

    public float groundDrag;
    public float airDrag;```
leaden ice
#

it should be more like... 0.05

#

or 0

#

since you're handling the speed limit thing yourself

swift falcon
#

setting the drag to 0 still doesn't fix the issue of the player accelerating past top speed

hexed pecan
#

Like how do you debug your speed

tiny delta
swift falcon
hexed pecan
#

I checked the SpeedControl method and it looks ok

swift falcon
#

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

leaden ice
#

what happens

#

12 is pretty fast

swift falcon
#

even if i set the top speed to 0 , it still moves , but it prints out 0

leaden ice
#

what happens if you set it to 1

mellow sigil
leaden ice
swift falcon
#

yeah

leaden ice
#

yeah so

#

this is for the reason i said above

swift falcon
#

oh i see..

leaden ice
#

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

swift falcon
#

so what would be the solution? running SpeedControl() before MovePlayer()?

leaden ice
#

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)

swift falcon
#

haha lol

#

well thanks for the help!

swift falcon
cedar pivot
#

how can i make a basic football shooting system like pes/fifa

#

not with skills etc.

leaden ice
#

It's probably quite complex

hexed pecan
#

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

cedar pivot
#

im not making fifa

hexed pecan
#

I read it as passing, not shooting for some reason

hexed pecan
cedar pivot
hexed pecan
#

Do you have anything currently?

#

Like how you control the ball and players etc.

cedar pivot
#

yeah passing, dribbling etc.

hexed pecan
#

So the real question is "how to get a random position in a goal" right?

#

Since you already have passing

cedar pivot
hexed pecan
sonic stream
#

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?

hexed pecan
#

@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;```
leaden ice
sonic stream
leaden ice
#

then to translate back into unity world space use the Grid component

sonic stream
#

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

velvet jackal
#

Better suited. So what if it’s bad

untold abyss
#

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?

somber nacelle
#

yes

tired sorrel
#

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

leaden ice
#

like where and when you start this coroutine

tired sorrel
#

you found it? xD

#

nearestTreeDistance = float.MaxValue;

leaden ice
#

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

tired sorrel
#

ok...

#

ill do that

leaden ice
#

As should nearestTree

sonic stream
leaden ice
tired sorrel
leaden ice
#

basically - providing the whole script would help

sonic stream
tired sorrel
tired sorrel
leaden ice
#

!code

tawny elkBOT
#
Posting 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.

tired sorrel
#

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)

leaden ice
#

should split it into several scripts

tired sorrel
#

hahaha

#

yeah i know

leaden ice
#

you're also doing a ton of reaching into other objects and playing with their internal states, not good practice

tired sorrel
#

oh, ok. idk how else i wuild do it but alr

leaden ice
#

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
brittle cobalt
#

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

leaden ice
tired sorrel
leaden ice
#

and to knopw what "collection point" is

leaden ice
#

it will grow harder over time to maintain this

#

but that's ok, we all have to make mistakes to learn

tired sorrel
#

cuild you come call? i will show you behaviour

leaden ice
#

Make a video, I can't do calls

tired sorrel
#

ok

leaden ice
tired sorrel
leaden ice
#

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 😵‍💫

gleaming patrol
brittle cobalt
#

cursor position

tired sorrel
tired sorrel
#

byw, i have the unity remote app open on my phone

leaden ice
#

or maybe IsCut is true for it

tired sorrel
leaden ice
brittle cobalt
#

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;
    }
}
tired sorrel
brittle cobalt
#

I made a version that works in java (usign libgdx) but it makes the camera unproject

tired sorrel
#

?

leaden ice
#

the code

tired sorrel
#

its in the pastebin?

leaden ice
#

oh

#

right

tired sorrel
#

xD

leaden ice
#

Invoke("walkfunction", 0.01f * Time.deltaTime); 😬

tired sorrel
#

?? 🙂

#

xD

leaden ice
#

you should really use a coroutine for this

#

this is a disaster lol

tired sorrel
#

Oh

#

xD

#

ok

leaden ice
#

that basically just means "wait one frame"

tired sorrel
#

AHHAH

leaden ice
#

it's not going to wait for that tiny amount of time accurately

tired sorrel
#

oh ok. il change later

leaden ice
#

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

sonic stream
tired sorrel
#

yeah, so when it is at a tree, it goes to find the next.

tired sorrel
gleaming patrol
brittle cobalt
leaden ice
leaden ice
gleaming patrol
tired sorrel
brittle cobalt
gleaming patrol
brittle cobalt
leaden ice
brittle cobalt
#

firePoint

#

I have both bullet and firepoint (starting point of bullet)

sonic stream
leaden ice
sonic stream
leaden ice
#

I was expecting you to click on that grid

sonic stream
sonic stream
tired sorrel
#

ill find someone else.

leaden ice
#

there's a lot of unknowns here

#

lots of places where things might go wrong

sonic stream
#

here it is

#

wait

#

lemme edit it,that is kinda old

gleaming patrol
#

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 🥲

sonic stream
sonic stream
gleaming patrol
brittle cobalt
# leaden ice what object has this script on it

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?

leaden ice
#

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.

gleaming patrol
gleaming patrol
brittle cobalt
leaden ice
#

or use Physics2D.IgnoreCollision when you spawn the bullet

brittle cobalt
#

Okay I will google it

sonic stream
leaden ice
#

Too complex for me to look at right now

#

You need to just debug it

tired sorrel
#

ok. i really cant figure it out. can someone please come call with me?

sonic stream
gleaming patrol
#

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 ?

leaden solstice
#

You're overwriting distance with invalid tree.

tired sorrel
#

i am starting to feel like unity is acting wrongly here

leaden solstice
#

What?

tired sorrel
#

cuz it just doesnt work. it does everything, it checks all trees distances.. and still doesnt activate the if(dist2 < nearestTreeDistance)

leaden solstice
#

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

tired sorrel
#

but that wuildnt matter tho? right

leaden solstice
#

Change it to at least this:

                if (dist2 < nearestTreeDistance && tree.GetComponent<Tree>().IsCut == false)
                {
                    nearestTreeDistance = dist2;     
                    nearestTree = tree.gameObject;
                }
tired sorrel
#

ok.

leaden solstice
#

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

tired sorrel
#

IT WORKS NOW

#

THANK YOU SO SO MUCH

leaden solstice
#

Alright, good luck now

tired sorrel
#

thank you.

#

have a good day

strong anvil
#

can someone call me and help with a simple script rq

vagrant blade
strong anvil
#

my collision script is not working

vagrant blade
#

And ... ?

uncut plank
strong anvil
strong anvil
stable rivet
rare lodge
#

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?

strong anvil
#

the sword

fiery oracle
#

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?

noble leaf
#

Hello

stable rivet
noble leaf
solemn mist
strong anvil
stable rivet
#

either you're not hitting OnCollisionEnter, or your tags are wrong, or IsAttacking is always false

stable rivet
strong anvil
noble leaf
pure sapphire
#

Hi, how I would be able to convert this to unity's new input system?

leaden ice
#

not that this is a good way to do it in the new system, but this is more or less a direct conversion

pure sapphire
leaden ice
#

there are many ways to do it

#

also I don't have much time rn

pure sapphire
#

ok fe thank you

lilac tree
#

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

fiery oracle
#

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?

leaden ice
fiery oracle
#

For Plastic SCM?

leaden ice
#

yes

fiery oracle
#

Hmmm, maybe I didn't. Good lead

leaden ice
fiery oracle
#

Thank you!

solemn mist
# lilac tree

couldn't u just do something like
Scene newScene = SceneManager.CreateScene(stringFromInputField);
and get the string from the input field or smthing

leaden ice
fiery oracle
#

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?

fiery oracle
#

@ Praetor

#

gitignore conf type file

fiery oracle
#

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)

pure sapphire
dreamy vapor
#

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

fluid lily
#

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.

dreamy vapor
fluid lily
#

Go to your material on the object, and right click the header, there should be a select shader option

dreamy vapor
fluid lily
#

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.

dreamy vapor
#

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

fluid lily
dreamy vapor
#

also the code snippet is just a copy/paste from the documentation actually

fluid lily
#

so that looks good, just switch "bg_apartment" for "_MainTex"

dreamy vapor
#

and bg_apartment is just meant to be that file

fluid lily
#

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.

dreamy vapor
#

Oh, so like it would be "_MainTex", bg_apartment?

fluid lily
#

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#.

dreamy vapor
fluid lily
#

m_Renderer.material.SetTexture("_MainText", MainTexture);

dreamy vapor
#

oh and i forgot to mention

#

bg_apartment is a .jpg

fluid lily
#

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.

dreamy vapor
#

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

fluid lily
#

Do you want the user in game, or user in editor to be able to select it?

dreamy vapor
#

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

fluid lily
#

Is the BackgroundChange script on that drop down or on the background itself?

dreamy vapor
#

the background itself

fluid lily
dreamy vapor
fiery oracle
#

Update: turning off find moved and renamed files seem to have fixed the issue!

fluid lily
#

Is the texture set in the editor for the MainTexture variable?

#

texture*

dreamy vapor
dreamy vapor
fluid lily
#

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

dreamy vapor
#

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

fluid lily
#

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.

dreamy vapor
#

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()

fluid lily
#

For now we are just testing, so either works.

dreamy vapor
#

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

fluid lily
#

What we will want to actually do is make a new method with three parameter's (one for each Texture).

dreamy vapor
#

Oh, I'm not interested in normal and metal

#

so i can likely take those out, right?

fluid lily
#

yes

dreamy vapor
#

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);
    }
}
fluid lily
#

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.

dreamy vapor
dreamy vapor
# dreamy vapor

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

dreamy vapor
#

just in case this is a better approach

fluid lily
#

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).

dreamy vapor
#

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?

fluid lily
#

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).

dreamy vapor
fluid lily
#

They go over how to hook into the events, though you will need to modify it for texture changing vs color changing.

dreamy vapor
fluid lily
dreamy vapor
#

@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

somber nacelle
#

why are all of your if statements doing the exact same thing? what's the purpose of the if statements?

dreamy vapor
#

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

dreamy vapor
somber nacelle
#

store the textures you want to assign into an array, then you could use the dropdown.value to access an index of the array

dreamy vapor
#

except instead of changing the 'background colors,' it's the texture of the quad

somber nacelle
#

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

dreamy vapor
#

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

somber nacelle
#

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

dreamy vapor
#

that's what I have on the dropdown right now

fluid lily
#

So we will just want to modify the original script a bit.

fluid lily
#

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 ().

dreamy vapor
#

okay, here's what i have so far

fluid lily
#

and instead of having to do all the if statements just have one line as fallows.

m_Renderer.material.SetTexture("_MainTex", Textures[myDrop.value]);
dreamy vapor
fluid lily
dreamy vapor
#

Note that the script is still attached to the quad 'Background'

#

And Background is what I dragged onto the dropdown

#

is this correct?

fluid lily
#

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.

dreamy vapor
#

because this is what i see

fluid lily
#

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.

dreamy vapor
#

Right, so I got to this:

#

And I tried running to see if the dropdown would change anything and it doesn't

fluid lily
#

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.

dreamy vapor
#

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.

fluid lily
dreamy vapor
#

nope

#

Dropdown doesn't change the quad's background

#

Here's my complete script btw

fluid lily
#

In the AssignTexture method do a debug.Log for the dropDown.value

dreamy vapor
#
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

fluid lily
#

This will let us know if it is atleast being called.

dreamy vapor
#

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 ^^

somber nacelle
fluid lily
#

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.

dreamy vapor
fluid lily
#

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.

dreamy vapor
#

Okay, I'll try that out in a minute. Also, if anything, I could try and make a fresh new dropdown instead.

fluid lily
dreamy vapor
#
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

dreamy vapor
#

but yeah, the texture is still not changing i think

somber nacelle
#

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

dreamy vapor
#

so i dragged the dropdown - background onto it

#

it still doesn't work though

somber nacelle
#

define "doesn't work"

dreamy vapor
#

so i changed the value here

#

and it didn't change the background

somber nacelle
#

any errors in the console? have you set up the dropwdown correctly?

dreamy vapor
#

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?

somber nacelle
#

you have to drag the object that has the method you want to call when the value is changed

dreamy vapor
somber nacelle
#

obviously yes

dreamy vapor
#

but hey

#

i got it working finally

#

so thank you for the help

somber nacelle
dreamy vapor
blazing remnant
#

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.

blazing remnant
#

I'm not exactly sure. The moving platform is an add-on and I haven't looked into that.

leaden ice
#

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?

blazing remnant
#

The platform's rotation would change the rotation of the object attached to the player, not any input.

leaden ice
blazing remnant
#

No, I want the game object's rotation to be relative to the platform's rotation.

leaden ice
#

I don't understand

#

draw a picture perhaps?

sterile tendon
#

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

blazing remnant
# leaden ice what does this mean then

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.

leaden ice
#

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

sterile tendon
# leaden ice huh

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()\"");

leaden ice
#

or use a RotationConstraint

sterile tendon
#

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()\"\'");
leaden ice
sterile tendon
#

well I made some changes to try to get it to work but /c

leaden ice
#

why don't you just launch python directly

sterile tendon
#

because it works fine as it is

leaden ice
#

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

sterile tendon
#

oh so I launch python itself?

leaden ice
#

yes

sterile tendon
#

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

drifting grail
#

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

leaden ice
#

you just have to do it right

leaden ice
#

!ide

tawny elkBOT
#
💡 IDE Configuration

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.

sterile tendon
# leaden ice you just have to do it right

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);
leaden ice
sterile tendon
#

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

leaden ice
#

idk what you mean by that

#

too vague, and I don't have context of what main.py is

sterile tendon
#

oh it's the script I'm trying to run

leaden ice
#

yes you would just do main.py as a command line argument.

#

not the code itself

sterile tendon
#

and I guess I need to show it the path right

drifting grail
#

I did everything in the linked wiki

#

I was just hoping for a bit more info than what's supplied here

cosmic rain
#

More than that you'll find in the actual docs.

wintry gust
#

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?

somber nacelle
#

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)

wintry gust
#

I was just hoping to avoid having to store a second variable.

haughty fiber
#

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?

somber nacelle
#

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)

haughty fiber
#

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;

?

somber nacelle
#

that's typically what you would do, yes. if your gravity variable is 9.81 (or just not already multiplied by deltaTime)

haughty fiber
#

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

somber nacelle
#

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

haughty fiber
#

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)

somber nacelle
#

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)

haughty fiber
#

Rad. I tested it out and it seems to all be working pretty well 👌

autumn cipher
#
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?

mellow sigil
#

well does it work?

autumn cipher
#

I'll try visualizing the raycast

#

but the origin is coming from the screen so

simple edge
#

You can have debug rays linger for a second

mellow sigil
#

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

autumn cipher
#
 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

somber nacelle
#

make sure you have gizmos enabled in game view

simple edge
#

And since it's direction, which is probably normalized, you might want to multiply that value by something to make it more noticable

autumn cipher
#

alright I'm can see the ray now, the ray is going downwards while looking at front for some reason

somber nacelle
#

nvm ignore that question i asked, it was dumb

autumn cipher
#

trying to raycast inside an imaginary circle bordered by the crosshair

autumn cipher
#

beautiful, thanks @mellow sigil and everyone else

void basalt
#

-100 % 36000 Why is this returning -100?

#

Shouldn't it return 35,900?

thin aurora
main shuttle
void basalt
#

I'm simply trying to wrap around the euler range

somber nacelle
void basalt
#

in fixed point format

dense moth
void basalt
#

That's not going to do anything

somber nacelle
#

honestly just perform the % operation then if the value is < 0 add it to the original number to get it to wrap

void basalt
#

yeah

#

thats what I was gonna do next lmao

somber nacelle
#
int mod = x % y;
int result = mod < 0 ? y + mod : mod;
void basalt
#

((a%b)+b) % b works nicely 🙂

somber nacelle
#

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

void basalt
#

Yeah was just testing that

somber nacelle
#

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

lean dust
#

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?

thin aurora
#

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?

lean dust
# thin aurora Does reloading the project fix it? Does updating to a newer patch version fix it...

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)

thin aurora
# lean dust afaik 2021.3.18f1 is the newest unity version What do you mean exactly by reload...

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.

lean dust
#

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/Unity to 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)

opal pine
#

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?

lean dust
plucky inlet
lean dust
# plucky inlet 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

#

not that any error in the logs would have pointed to that

plucky inlet
#

Usually play mode freeze is caused by some infinite loop. But maybe you already filtered that out

lean dust
#

or that you would expect if you change nothing else about the project, the same old sdk from 3 months ago should still work

plucky inlet
#

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.

lean dust
plucky inlet
#

Only Photon Devs will know probably 😄

void basalt
#

(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

tepid river
#

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??

lucid valley
#

so it is correct

tepid river
#

i have the parent select tho

#

but the arrows are shown at the childs pos

lucid valley
#

select the child and show a picture of that

tepid river
#

here is the child:

#

and here the parent.

#

notice that the visual arrow indicators are wrong for the parent

lucid valley
#

oh, i get what you mean now

#

uh, i think theres a setting somewhere

#

let me try to find it

tepid river
#

thanks it super confusing.
for the spaceship, unity puts the visual indicated position at some random deep nested child, far behind the ship

lucid valley
#

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

tepid river
#

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

vagrant blade
#

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.

tepid river
#

i have no idea lol

#

i cant find anything on google, how would i change in/out of pivot mode?

vagrant blade
#

At the top of the scene window is a drop down to toggle between pivot and center mode.

tepid river
vagrant blade
#

Pivot is almost always the setting you want to be on.

tepid river
#

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 ❤️

vague slate
#

How can I create my own custom project settings for my package?

void basalt
#

even when I cast to int, it's still 3

#
        Debug.Log((int)myFloat);``` This also gives me 3
buoyant crane
void basalt
#

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

buoyant crane
leaden solstice
void basalt
#

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

leaden solstice
void basalt
#

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?

leaden solstice
#

Why not just go with Round?

void basalt
#

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

leaden solstice
#

Eh, good luck with that, sounds like PO

#

Pow is not very fast for sure, it’s basically sqrt and more

severe maple
#

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

hidden verge
#

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.

autumn cipher
#
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
sleek bough
sleek bough
#

Out of range means you accessing index that doesn't exist

autumn cipher
#

yes

#

and it's right there

sleek bough
#

Again, put the debug message and see what is actually being accessed and fix it

autumn cipher
#

I don't know how to do that

rain minnow
#

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 . . .

sleek bough
autumn cipher
#

the index reaches to 5 somehow, what the hell

rigid flower
#

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

thin aurora
rigid flower
#

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

rigid flower
#

ok i figured it out... weird that its not documented anywhere

red snow
#

Any resource on how one would design a game’s code architecture?

rigid flower
red snow
#

Any suggestions on article or video lectures?

rigid flower
#

not really...

red snow
#

No problem will research more about the software architecture thanks

lethal vigil
#

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?

waxen kayak
#

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);
tepid river
#

gotta change local rotation if you dont want to overwrite the parent ones

waxen kayak
#

I don't think that will work then

#

the angle calcuations will be messed up then

#

no it doesn't

leaden ice
waxen kayak
#

well

#

okay but what do I do to do that?

leaden ice
#

Convert all the positions and directions to local space

#

Then do the math

waxen kayak
#

Is that really it?

#

I'll try

#

okay how the hell do I do that

vestal oar
#

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

waxen kayak
#

okay I changed all the rotations and positions into local

#

well

#

oh god

placid summit
waxen kayak
#

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

placid summit
#

you can get and set in world space no problem. But try starting with a turret that points down +Z

hexed pecan
#

Im confused why would you want to calculate it in local space?

waxen kayak
#

the turret is on a rigidbody that can move

#

and rotate

hexed pecan
#

Still

#

I get the rotations being local

#

But positions?

waxen kayak
#

I don't know why I would set that to local

placid summit
#

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

hexed pecan
#

Maybe im missing something

vestal oar
#

If you're trying to move a child with the parent, local space is 100% better

waxen kayak
#

let me try to illustrate it in paint

hexed pecan
#

Is it a 2D game?

waxen kayak
#

no

#

it's 3d

#

I have a ship that can move and rotate

#

and it has a laser turret on it

hexed pecan
#

The turret is rotating on the z axis or what?

#

Maybe screenshot your turret setup

waxen kayak
#

which is supposed to look in the direction of the target

vestal oar
#

Have you tried LookAt()?

placid summit
#

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

waxen kayak
#

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

hexed pecan
#

This doesnt really work if your Z axis is up

#

Unless if you wanna do some extra quaternion math

waxen kayak
#

well

#

I can change that then

hexed pecan
#

Try changing it so that the turret's forward is the Z axis

placid summit
#

so you want to rotate 1 part around y axis and one on the z?

#

x surely

waxen kayak
#

yes

placid summit
#

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

waxen kayak
#

it's a space ship

hexed pecan
#

Unless if you give it a different up-vector which you dont

waxen kayak
#

Alright I'm changing the axises so up actually points UP

placid summit
#

you need to rotate up and down on local x angle, but calculating the angle would be tough if spaceship can twist around

hexed pecan
waxen kayak
#

well yes the thing holding the ball could move to any angle but only around Up axis

hexed pecan
#

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

waxen kayak
#

or on that picture the forward

#

okay I changed it to this, now it actually points up

hexed pecan
#

Okay but is the blue arrow now pointing behind it

#

Or are we seeing the back of the turret?

waxen kayak
#

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

placid summit
#

any moving object is best when modelled to face down +Z axis. This is the standard way of doing things

hexed pecan
waxen kayak
#

well

hexed pecan
#

I didnt realize it's looking up

waxen kayak
#

the ball was

#

the base of it and the thing that only rotates horizontally wasn't right

hexed pecan
#

Oh you had the base selected

#

Nvm then its all good

placid summit
#

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

hexed pecan
#

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.

waxen kayak
#

now you see

#

I used that

#

but it's weird

hexed pecan
waxen kayak
#

when the angle difference get's close to 0 it starts jumping around

waxen kayak
#

it only jumps a few degrees but that will totally throw off aim in space combat

hexed pecan
#

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

waxen kayak
#

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

hexed pecan
#

How did you do it

waxen kayak
#

what?

hexed pecan
#

Cant say much without seeing the code

waxen kayak
#
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

hexed pecan
#

How to format code: !code

tawny elkBOT
#
Posting 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.

waxen kayak
#

what damn character is that

hexed pecan
#

`

waxen kayak
#

it just ins't on my keyboard

bold kestrel
#

Left of 1 on the qwerty layout

hexed pecan
#

Backtick

west lotus
#

It is

hexed pecan
#

Which is qwerty

bold kestrel
#

oh

waxen kayak
#

' I only hav ethis

#

so yeah it isn't

#

I'll just learn the ASCII code

bold kestrel
#

For now, you can copy this
```

waxen kayak
#

´

#

wait holy shit I found it

#

it isn't marked

bold kestrel
#

nope

#

that's backwards

waxen kayak
#

bruh

#

right it is

waxen kayak
#

could I juse use lookat at set x and z rotation to zero?

dry yoke
#

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.

hexed pecan
#

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);```
tepid river