#archived-code-general

1 messages · Page 43 of 1

solemn latch
#

It doesnt help

#

I may have follow it wrong

#

I copied that custom script i could return vector3 without issue but still the moment it became a list it explode

signal cape
#

hi there, i got quite a problem on my hand. I am trying to make an enemy in a 2d game that would attack with a laser and that laser would follow the player for 5 sec and then stop :

#

but when the player move

woven dust
#

Been trying to fix this for a full day

#

Any ideas?

signal cape
woven dust
#

Theres no other instances of the script calling it, ive tried assigning it with gameobject.find on awake and start, manually assigning it in the inspector

#
playerOne.transform.localPosition = new Vector2(1,1);

player one is a public gameobject, tried using transform too

hard sparrow
#

Has anyone had the issue where if you click an error log, it doesn't show you any any actual log and instead rapidly selects a class and spams the console with more of the same exception?

#

I'm guessing that means the error is inside an update loop?

solid herald
#

i didnt understood that

thin aurora
solid herald
lucid valley
#

you need that in order to set the parent of the newly spawned gameobject

solid herald
lucid valley
#

sure

#

e.g

solid herald
#

yes

#

i have it

lucid valley
#

ok

solid herald
#

[SerializeField] GameObject Generations;

lucid valley
#

then just do cs Instantiate(building1, new Vector2(buildingPos, hBuilding1), Quaternion.identity, Generations.transform);

solid herald
#

oh

#

it doesnt show any error now

#

let me test it

signal cape
#

guys in a 2d rotaion space how to make an object slow down when it turns on way and tries to turn the other way?

wide fiber
#
 [SerializeField] float TimeBtwnSpawn = 1f;
    float NextTimeSpawn;

    [SerializeField] bool _usePool;
    [SerializeField] Enemy01 _enemy01;
    public ObjectPool<Enemy01> _pool;

    private void Start()
    {
        _pool = new ObjectPool<Enemy01>(() =>
        {
            return Instantiate(_enemy01);
        }, enemy01 =>
        {
            enemy01.gameObject.SetActive(true);
        }, enemy01 =>
        {
            enemy01.gameObject.SetActive(false);
        }, enemy01 =>
        {
            Destroy(enemy01.gameObject);
        }, false, 10, 20);
    }

    private void Update()
    {
        SpawnEnemyOne();
    }
    void SpawnEnemyOne()
    {
        if (Time.time > NextTimeSpawn)
        {
            NextTimeSpawn = TimeBtwnSpawn + Time.time;
            var enemy01 = _pool.Get();
            enemy01.transform.position = new Vector2(Random.Range(-4.3f, 4.3f), 2.73f);
        }
    }```
hi guys sorry, but how do i so called "remove the game object"? in the old object pooling system, i can just setActive(false) on the script that attached to that object. But this is the new one, it said "_pool.Release();" on that script, but it has a null error
wide fiber
# dusk apex Show the console error.

it said there's a null reference exception error on this line cs private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("Ground")) { _pool.Release(this); <---- this line } }

dusk apex
#

_pool is null

#

NREs occur because a variable has attempted to access it's member but has not yet been properly assigned a reference or is currently assigned a null reference.

wide fiber
# dusk apex _pool is null

oh ok. now i put ? after _pool, it works ty but now it didnt disappeared.

erm.... i think i wanna give up on this new input object pooling system. It's so complicated. Sorry but is the old object pool system is as good as the new one? in terms of garbage collecting or FPS dropping etc? because if its as good as new one, i will jsut use the old one haha

wide fiber
dusk apex
#

Where you'd simply need to reference the object above with said script component and then you'd be able to access the public _pool member.

wide fiber
swift falcon
#

on discord, I mean*

dusk apex
#

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

swift falcon
#

What the

#

I don't know how to do that

hexed pecan
#

Read the "Inline Code" section of the bot's message above^

swift falcon
#

So I tried to make a coding on the character to walk properly (Down, Left, Right, Up) with an animation so I made a script for it, it has no issues but seems like it won't work on it since the character just walk with straight line

#
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;

    private bool isMoving;

    private Vector2 input;

    private Animator animator; 

    private void Awake()
    {
        animator = GetComponent<Animator>(); 
    }

    private void Update()
    {
        if (!isMoving)
        {
            input.x = Input.GetAxisRaw("Horizontal");
            input.y = Input.GetAxisRaw("Vertical");

            Debug.Log("This is input.x" + input.x);
            Debug.Log("This is input.y" + input.y);

            
            if (input.x != 0) input.y = 0;


            if (input != Vector2.zero)
            {

                animator.SetFloat("moveX", input.x);
                animator.SetFloat("moveY", input.y);

                var targetPos = transform.position;
                targetPos.x += input.x;
                targetPos.y += input.y;


                StartCoroutine(Move(targetPos)); 
            }

        }
    }


    IEnumerator Move(Vector3 targetPos)
    {
        isMoving = true;

        while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
            yield return null; 
        }
        transform.position = targetPos;

        isMoving = false; 
    }
    

 
} ```
strong forge
#

Ok, so, I am currently making a grand strategy game, and I've made a system which can load provinces from an image file, similar to what you'd see in a paradox grand strategy game, it all works, there's no problem with that. I can get all the information of a province by simply clicking on it, and it's relatively performant, great stuff.

Now, my issue is, that I need to, like, overlay these provinces with the color of the country they are apart of. And I am not asking how to do that, it's probably very complicated. I just have no idea what to search for, so I am looking if someone more experienced than me could lead me into the general direction, since I believe that just storing the pixels of the province and then having a second texture on which I paint those pixels everytime I need to change the color, doesn't sound that performant, and I am sure there is a better way to do it with like some kind of shader which associates 2 colors or something.

amber brook
#

Hey Guys I am having weird issue with Unity, So I am making a runner game, and I have a layer for objects I want to kill the player, Problem is part of the colliders is a vehicle, I want players to only be killed by front part and be able to climb the roof, so I created an empty game Object in the vehicle prefab, set the collider the position of the roof, then set the layer to be default so it doesnt kill the player, problem is that it makes the rest of the vehicle not kill the player whereas other parts are set to the layer thats supposed to kill the player what could be the problem

spark flower
#

if i run code OnEnable, shuld i also run it on Start? i know start runs once and never again but does OnEnable run when Start runs?

lucid valley
#

OnEnable will run before start

#

but also every time the gameobject becomes active again (unlike Start that only ever runs once)

pearl otter
#

What is the best way to check if the player is moving to change the animation to a walking animation? I tried checking the distance between the current position and the last position but its saying the player is moving when its idle. Any ideas?

hexed pecan
#

Or do movement forces

#

And change the Animator's parameter there

pearl otter
pearl otter
hexed pecan
#

Probably more performant than a distance check 🤔

hexed pecan
#

But if you need to check distance (to avoid walking while not moving, feet sliding etc), you can do it

pearl otter
# hexed pecan Probably more performant than a distance check 🤔

Hmm..
Unity doesn't have a function to check if a key is held down so I would need to keep variables for W A S D when they are pressed and released and then compare those values to see if any of them are not pressed down so I can change from Walk to Idle animation

hexed pecan
pearl otter
#

I'm using Unity's new input system

#

You can only check if keys were pressed the frame

#

Unless if it checks if its held down

hexed pecan
#

I'm pretty sure you can poll input with the new system too

pearl otter
#

Is wasPressedThisFrame true if the key was pressed in a previous frame and is still held down?

hexed pecan
#

Looks like you can use context.ReadValueAsButton

#

Even if not, you could store it in a bool

pearl otter
hexed pecan
#

Oh yeah you mentioned keeping it in a variable

pearl otter
#

But then like I said, each frame that would be checking 4 variable if they are pressed down and if they have been released, and then checking if any are still being held. I am explaining this horribly but it doesn't sound very efficient ._.

hexed pecan
#

No I hear what youre saying. But hmm you could just update the animator parameters right as you receive the input?

#

No need to store it anywhere

#

Im curious though how your character is moving then? Don't you already have variables for its movement direction?

pearl otter
#

Uhh

#
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        move = transform.right * x + transform.forward * z;
        controller.Move(move * newSpeed * Time.deltaTime);```
#

That is what I have

#

Also this is what I meant before by using variables...

        if (Keyboard.current.wKey.wasPressedThisFrame) wPressed = true;
        if (Keyboard.current.aKey.wasPressedThisFrame) aPressed = true;
        if (Keyboard.current.sKey.wasPressedThisFrame) sPressed = true;
        if (Keyboard.current.dKey.wasPressedThisFrame) dPressed = true;

        if (Keyboard.current.wKey.wasReleasedThisFrame) wPressed = false;
        if (Keyboard.current.aKey.wasReleasedThisFrame) aPressed = false;
        if (Keyboard.current.sKey.wasReleasedThisFrame) sPressed = false;
        if (Keyboard.current.dKey.wasReleasedThisFrame) dPressed = false;

        if (wPressed || aPressed || sPressed || dPressed)
        {
            animator.SetBool(idleAnimID, false);
            animator.SetBool(runAnimID, true);
        }
        else
        {
            animator.SetBool(idleAnimID, true);
            animator.SetBool(runAnimID, false);
        }```
#

Actually I could use else if's which would make it a bit better but still lol

hexed pecan
#

Oh I assumed you were using Input actions

#

Which are event based

#

You wouldn't have to poll it

pearl otter
#

I don't know how to use those 😂

leaden ice
pearl otter
leaden ice
#

Use an input action

pearl otter
#

Idk how ._.

leaden ice
#

Bind it to the up/left/right/down composite of those buttons

leaden ice
small void
#

Recently stumbled upon this video (https://www.youtube.com/watch?v=Jufdyjl6poo&t=219s) and was quite intrigued by the section on a multi scene workflow. I cant seem to find many resources on setting up such a thing, so wondering if anyone on here knows of any more comprehensive resources or reading on this topic. Thanks

Sign up to Milanote for free with no time limit: https://milanote.com/gamedevguide - Let's explore 5 things you can do to improve how you're working in Unity. Got any tips of your own? Let me know below 👇🏻

Better Version Controls:
Plastic - https://www.plasticscm.com/
SVN (Subversion) - https://subversion.apache.org/
Perforce (Industry Standar...

▶ Play video
strong forge
pearl otter
sacred canyon
#

Whenever I make a build for a game and I have unused assets in my project, does my build include those unused assets? If so how do I make it to where those unused assets don't get included?

sacred canyon
#

So I shouldn't have to worry about migrating unused assets anywhere or anything like that when I make my builds?

sonic stream
#

so i am trying to generate objects in a grid position between the origin point of the transform,but it doesn't instantiate completely,but stops at like a distance of 1-2 units from the mouse,for context the grey knob is the mouse position when clicked

            var size = Input.GetKeyDown(KeyCode.LeftShift) ? (mousePos - transform.position).normalized : (mousePos - transform.position);
            Vector2Int completeSize = Vector2Int.RoundToInt(size);
            for (int x = 0; x < size.x - 1; x++)
            {
                for (int y = 0; y < size.y - 1; y++)
                {
                    testObjects[x,y] = Instantiate(testObject, new Vector2(x, y), Quaternion.identity);
                }
            }
#

also i am using ScreenToWorldPoint

leaden ice
sonic stream
leaden ice
sonic stream
# leaden ice you should be doing CeilToInt and omit the -1 or FloorToInt and include the -1 (...

            var size = Input.GetKeyDown(KeyCode.LeftShift) ? (mousePos - seekerRigidBody.position).normalized : (mousePos - seekerRigidBody.position);
            Vector2Int completeSize = Vector2Int.CeilToInt(size);
            testObjects = new GameObject[completeSize.x + 1, completeSize.y + 1];
            for (int x = 0; x < size.x; x++)
            {
                for (int y = 0; y < size.y; y++)
                {
                    testObjects[x,y] = Instantiate(testObject, new Vector2(x, y), Quaternion.identity);
                }
            }

so something like this?

leaden ice
sonic stream
#

i want to make sure that a cube is always instantiated regradless of grid size

leaden ice
magic harness
#

Hey Guys.
I'm working with UI right now and i have a scroll list in which i instantiate some prefabs on start.
Thing is. Those prefabs have buttons that i need to change/register the callBack function from.

Thing is. im adding a function as a listener and its going in the function

here is the code ```c

public void ShowFreeSurvivors(Transform activityTransformIcon)
{
survivorScrollView.parent.gameObject.SetActive(true);
foreach (Survivor survivor in survivors)
{
Transform child = survivorScrollView.GetChild(0).GetChild(0).Find(survivor.name);
if (child == null)
{
Debug.Log(survivor.name + " returned null, something is wrong with survivorManager");
continue;
}
if (survivor.isBusy) child.gameObject.SetActive(false);
child.GetComponent<Button>().onClick.AddListener(() => OnSurvivorSelected(activityTransformIcon, survivor));

    }
}
#
    private void OnSurvivorSelected(Transform activityTransformIcon, Survivor survivor)
    {
        Debug.Log("Got in here");
        activityTransformIcon.GetComponent<Image>().sprite = survivor.icon;
        survivorScrollView.parent.gameObject.SetActive(false);
        //next we are going to have to pass the survivor to the activity so he can run it whenever player clicks on run button
    }
magic harness
#

Debug never prints, buttons dont do anything. no callback function is register on the inspector

leaden ice
magic harness
#

the scroll list goes up and down tho

leaden ice
#

adding listeners with AddListener won't add one to the inspector

#

that's only for persistent listeners

magic harness
leaden ice
#

Use Debug.Log to make sure you're getting to the code that calls AddListener

magic harness
#

im getting there already done that

#

button is there as well

#

doesnt return null i mean

leaden ice
#

or survivors has no children

#

see if you can get a positive Debug.Log after that null check

magic harness
#

nah, they have.

leaden ice
#

just to make sure

#

and rule that out

magic harness
#

ok

#

1 sec

#

test passed. it prints

leaden ice
#

Does it animate/fade/change color/etc?

magic harness
#

no, not at all

leaden ice
magic harness
#

it is interactable

#

nah that's fine cause other buttons work

#

only these ones doesn't

leaden ice
#

then something is blocking this one

#

another UI element

#

or the canvas it is on is missing a Graphic Raycaster

#

keep your EventSystem selected and look at the preview window at the bottom of the inspector while the game is running. Observe what the preview window says about which object(s) the mouse is hovering over

magic harness
#

Bingo my friend

#

Another part that is work in progress was blocking it. another panel that i still have to populate and add into the navigation logic.

#

Thanks! Owe you one!

sonic stream
orchid anchor
#

How do I convert quaternions to euler in JavaScript ?

#

I'm receiving the quaternions x, y, z and w values on a website, I want to convert that into euler angles. How do I do that ?

noble leaf
#

Good afternoon

#

I try make a game of sumô

#

And my codings not working

#

Movimentation:

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(Collider))]
public class Movimentation : NetworkBehaviour
{
    public float moveSpeed = 5f;
    public float jumpForce = 10f;
    private bool isGrounded = true;

    private Rigidbody rb;

    public GameObject player;

    void Start()
    {
        rb = GetComponent<Rigidbody>();

        if(isLocalPlayer){
            rb = GetComponent<Rigidbody>();
            rb.centerOfMass = new Vector3(0, -0.5f, 0);
            Cursor.visible = false;
            Cursor.lockState = CursorLockMode.Locked;
        }
    }

    void Update(){
        if(isLocalPlayer){
            Stabilization();
        }
    }

    void Stabilization(){
        if(Input.GetKeyDown(KeyCode.M)){
            Vector3 newRotation = new Vector3(0f, 0f, 0f);
            player.transform.rotation = Quaternion.Euler(newRotation);
            rb.Sleep();
        }
    }

    void FixedUpdate()
    {
        if(isLocalPlayer){
            float horizontalInput = Input.GetAxis("Horizontal");
            float verticalInput = Input.GetAxis("Vertical");

            Vector3 movement = new Vector3(horizontalInput, 0f, verticalInput) * moveSpeed * Time.deltaTime;
            rb.MovePosition(transform.position + movement);

            if (Input.GetButtonDown("Jump") && isGrounded)
            {
                rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
                isGrounded = false;
            }
        }
    }

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.CompareTag("Ground") && isLocalPlayer)
        {
            isGrounded = true;
        }
        else if (other.gameObject.CompareTag("Player"))
        {
            Vector3 repulsionDirection = transform.position - other.transform.position;
            rb.AddForce(repulsionDirection.normalized * 10f, ForceMode.Impulse);
        }
    }
}
#

Câmera:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;

public class FirstPersonCamera : NetworkBehaviour
{
    public Transform characterBody;
    public Transform characterHead;

    float sensitivityX = 70.0f;
    float sensitivityY = 70.0f;

    float rotationX = 0;
    float rotationY = 0;

    float angleYmin = -80;
    float angleYmax = 80;

    float smoothRotx = 0;
    float smoothRoty = 0;

    float smoothCoefx = 0.85f;
    float smoothCoefy = 0.85f;

    public Camera playerCamera;

    void Start()
    {
        if(isLocalPlayer){
            Cursor.visible = false;
            Cursor.lockState = CursorLockMode.Locked;
        }

        if(!isLocalPlayer){
            playerCamera.enabled = false;
        }else{
            playerCamera.enabled = true;
        }
    }

    private void LateUpdate()
    {
        if(isLocalPlayer){
            transform.position = characterHead.position;
        }
    }

    void Update()
    {
        if(isLocalPlayer){
            float verticalDelta = Input.GetAxisRaw("Mouse Y") * sensitivityY;
            float horizontalDelta = Input.GetAxisRaw("Mouse X") * sensitivityX;

            smoothRotx = Mathf.Lerp(smoothRotx, horizontalDelta, smoothCoefx);
            smoothRoty = Mathf.Lerp(smoothRoty, verticalDelta, smoothCoefy);

            rotationX += smoothRotx * Time.deltaTime;
            rotationY += smoothRoty * Time.deltaTime;

            rotationY = Mathf.Clamp(rotationY, angleYmin, angleYmax);

            characterBody.localEulerAngles = new Vector3(0, rotationX, 0);

            transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
        }
    }
}
rain minnow
noble leaf
#

And my players are flyng in arena

noble leaf
orchid anchor
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.

orchid anchor
#

When we convert the transform component to JSON, it is in this form:

simple egret
#

Googling "quaternion to euler angles" yields a Wikipedia page first result, in which if you scroll down, shows a C++ example converter method

orchid anchor
#

in m_LocalRotation the object's rotation is in quaternions.

orchid anchor
noble leaf
simple egret
orchid anchor
#

The 4 values on top are x, y, z, w respectively

#

the array is the generated angles

#

it should be [45, 0, 0]

rain minnow
# noble leaf Somebody help?

Use a bin or paste site to put your code then send us the links. The code you put takes up too much space in chat . . .

simple egret
#

Unity's axis setup is not standard, the vector should be rotated so Z faces up, and Y forwards

orchid anchor
#
console.log(x, y, z, w, qte([z, y, x, w]).map((a) => a * (180/3.1415926)));
vale wren
#

i need to make an item representation of a weapon, but i also need to store levels. should i use scriptable objects for this? in the past i had to do weird workarounds because scriptableobjects aren't modifiable

polar marten
vale wren
#

thanks

polar marten
#

there are a few approaches to this

#

take a look at prefab variants

#

you can variant out the UGUI and in-game representations of your weapon

#

e.g.

orchid anchor
polar marten
#

your project folder:

Role                     Name of Asset
[1: Prefab]              Base Weapon
[2: Prefab variant of 1] AK47
[3: Prefab variant of 2] AK47 (UGUI)
[4: Prefab variant of 2] AK47 (Playermodel)
[5: Prefab variant of 2] AK47 (Dropped)

for example, here is the hierarchy of AK47 UGUI

AK47 (UGUI)
 Inspector:     Weapon Component
                AK47 Component
            [+] RectTransform
 -> Image
 -> Text Label
    ... 
polar marten
# vale wren thanks

ultimately scriptable objects will be low value. the 3 fields of the weapon name, its cost or whatever - that stuff is not saving you any time to build this whole thing around. you'll still eventually need to make a bunch of prefabs representing the weapon in different contexts.

vale wren
#

thx!!!

polar marten
#

@vale wren so when you save levels, you meant upgrades for the weapon right? I suppose those could be components on the AK47 prefab. those will automatically propagate down to the prefab variants. that way, when you want to visualize the current level, you can add an object to AK47 (UGUI) like a label that references those

vale wren
#

yeah exactly

polar marten
#

to "turn" a UGUI into a Dropped weapon is trickier - you might want a different hierarchy, one where you separate the logical part from the graphics part. so something like

AK47
 Logical
 Graphics
  UGUI
AK47
 Logical
 Graphics
  Dropped
AK47
 Logical
 Graphics
  Playermodel
#

for the sake of designing easily, you can keep these as prefab variants. then, in game, when you want to "drop" an item, Instantiate the Logical game object (which copies it), then instantiate a fresh dropped graphics and destroy the ugui graphics

#

this is fine if you really want to commit to the Unity way of organizing your game, it will work and it will take advantage of editor features

#

and not be painful

#

but it will make it a little harder to know what's going on, because it's hard to enforce a hierarchy in the editor as opposed to code*

#

if all of this stuff is pretty lightweight, you can have one prefab of this form: all three graphics are present. then toggle between them and don't Instantiate.

AK47
 Logical
 Graphics
  UGUI (active)
  Dropped (inactive)
  Playermodel (inactive)
#

this is what i usually do

#

it's tricky because AK47 expects to be recttransform2d to be on a UI - so in reality, UGUI is always separate

#

and has a reference to an AK47 game object that lives in 3D space but has no graphics

#

this is a very ECS approach. indeed, ECS is really good for making something like an FPS

#

@vale wren hope this helps

vale wren
#

thank you!!!! this is a much cleaner system than whatever the hell i was doing before

polar marten
#

lol

#

okay cool

#

this recttransform thing is going to be a pain point

#

just a heads up

#

remember at runtime there are no prefab variants, and you can also move things around. i suggest designing with the UGUI object, then moving it at runtime into your UGUI hierarchy. it will still reference the correct weapon.

#

so something of the form

AK47
 Logical
 Graphics
  AK47 UGUI

when you hit play, move the UGUI object where it needs to be. then this becomes

AK47 (Clone)
 Logical
 Graphics
Camera
 Canvas
  Panels
   AK47 UGUI
polar marten
#

AK47 UGUI itself can be a prefab variant of an Item so all you're doing is overriding the sprites

pearl whale
polar marten
#

that way if you want to change the look of the icons in your inventory gradually, you can

leaden ice
#

you can replace hundreds of lines of code with 3

polar marten
#

@vale wren prefab variants, used wisely, are like a superpower and obsolete a lot of scriptable object workflows for your early game development

#

prefabs are nice when most of the work is defining a weapon's behavior as a composition of other smaller pieces.

pearl whale
polar marten
#

lots of advantages.

potent sleet
pearl whale
leaden ice
#

your code is insanity

#

it was written by a raving mad lunatic

pearl whale
#

😭

simple egret
#

oh god I made the mistake expanding it

pearl whale
leaden ice
#

what are you expecting it to do

#

what does it do instead

agile ice
#

i have a collision-based flag in LateUpdate that should get initialized by code executed in OnTriggerStay, and according to the unity docs on the order of execution, OnTriggerXXX gets called first beforeLateUpdate. however, during playmode, the the script is behaving as if LateUpdate gets called first before OnTriggerStay, resulting in the flag not getting initialized before LateUpdate code executed. this behavior occurs inconsistently between entering playmode, where the flag sometimes gets initialized by OnTriggerStay before its used by LateUpdate, and sometimes it doesn't. any ideas as to how to resolve this issue??

pearl whale
leaden ice
#

you'd have to explain exactly what you're trying to do

#

to get a better suggestion on what to do

leaden ice
#

Have you attached this script to some object?
which object's size are you looking at?

#

Is Time Scale being changed?

#

(looks like it is)

pearl whale
#

normally the text grows and escalates indefinitely

leaden ice
#

It will really help solve your issues

polar marten
#

keep it up!

polar marten
leaden ice
pearl whale
#

contain texet

polar marten
#

if you have some animation knowledge

sonic edge
#

Hello, I'm curently creating a simple hit detection script that would be on the sword of my character (which has a box collider 2D). I wanted to know how it is possible to access to the script of the hit element (without the GetComponent<>() function which isn't working because I have severals enemy scripts) ?

polar marten
#

you are tweening a pulse

polar marten
#

one is called DOTween, if you want to tween in code

pearl whale
#

Is Time Scale being changed? yes

#

I have findedd

polar marten
#

you can also do this using the built in unity animation tools.

#

it's worth learning how a dope sheet works too!

#

@pearl whale

#

while this isn't exactly what you're doing, you can modify the parameters to do this thing you are trying to do

#

don't say that' snot exactly what it is

#

i know what you wrote

#

you have to try to use the more general thing to get what you want

pearl whale
#

In other script timeScal set to 0.1f

polar marten
#

don't mess with time scale at all

#

part 2 is, to deal with "pressing" on stuff, look up Event System

polar marten
#

good luck!!

pearl whale
#

thx

slow trout
#

When creating a script from Visual Studio, a namespace will be generated for it. Anyone know how to enable this behaviour when creating a script from Unity?

spare otter
#

Hey, I am creating a fps view game and I want to add controller controls but the joystick Y Axis does not work. Is that normal ?

stable rivet
#

just open up project settings and search for namespace

slow trout
#

With your example it will only be RootNamespace as namespace

stable rivet
# slow trout Yeah, but I realized this will put every script under this namespace. If I want ...

to be honest, I would just add to that root namespace - although I typically create my scripts in rider for this exact problem. if you really wanted to, there are ways to get what you want
https://stackoverflow.com/questions/64214665/automatically-add-namespace-to-unity-c-sharp-script may be useful

#

but its just a lot of fuss for something that ultimately is done for free through your ide

slow trout
stable rivet
slow trout
stable rivet
#

/s

slow trout
pure dragon
#

generally speaking, is having two command patterns in a single project messy code? Im asking as I am thinking of implementing a command pattern for actions to perform, and a command pattern for the state machines that activate them. is this messy?

soft shard
# slow trout Yeah, but I realized this will put every script under this namespace. If I want ...

If you really wanted to, you could build your own system with the AssetPostProcessor: https://docs.unity3d.com/ScriptReference/AssetPostprocessor.html
Then check if the asset imported/creeated is a script file, and use System.IO to get the folder path (or string-split the params of OnPostprocessAllAssets for example), then you can use AssetDatabase to re-import the script, or you can make a custom Editor window to create new scripts from and set a namespace before your window creates the asset file - though both approaches would require Editor scripting and probably take time to setup correctly, just options you could explore

polar marten
#

i was scanning around

slow trout
polar marten
#

👀

#

based on the folder structure

#

do you use Resharper?

slow trout
#

Only at work

#

Maybe I should install this here

#

But would reshaper solve my particular problem? 😄

stable rivet
slow trout
#

Exactly

fiery bridge
#

Im trying to make the door open when I hit F but if i do it then the Door Opens and closes at the same time (can someone pls help)

`void Update()
{

    RaycastHit hit;
     if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, InteractRange)) {
        if(hit.transform.tag == "door")
        {
            Debug.Log("Raycast hit the Door!");
            if(!DoorIsOpen)
            {
                if (Input.GetKeyDown(KeyCode.F))
                {
                    animator.SetBool("DoorIsOpen", true);
                    DoorIsOpen = true;
                    Debug.Log("pressed F Door is now Open!");
                }
            }

            if(DoorIsOpen)
            {
                if (Input.GetKeyDown(KeyCode.F))
                {
                    animator.SetBool("DoorIsOpen", false);
                    DoorIsOpen = false;
                    Debug.Log("pressed F Door is now Closed!");
                }
            }
        }
    }
}`
polar marten
slow trout
#

I just solved it by naming my OG namespace starting with a _. I'm ok with the solution.

polar marten
#

hope this helps

slow trout
#

Thanks, that's what im using 😄

polar marten
#

this is for when you screate it in unity

livid topaz
#

need some code advice here, not sure if ive found a really smart thing or im building a time bomb

// MoveStyles (a base class)
  public abstract void Jump();
  protected virtual void PerformJump(float f)

// Classic (a move style)
  [SerializeField] private float m_JumpForce = 8;
  public override void Jump() => base.PerformJump(m_JumpForce);

// Grounded state
  Player.MoveStyles.Jump();
#

this is so i can add variables to the derived classes without inheriting them or overriding them in any way, just overriding the way that the base class gets ahold of them

#

is this brilliant or awful

stable rivet
potent sleet
#

not code related

dusk apex
livid topaz
#

but then i cant pass variables down from a derived class unless that variable is part of the base class itself

#

not without exposing those variables to other aspects of the code, that is

dusk apex
#

What do you mean? You'd just implement the function.. no passing necessary.

livid topaz
#

i ask the player's moveStyle to apply air friction, the style itself has its own variables that the base class - MoveStyle - does not contain

dusk apex
#

Right. What about it?

livid topaz
#

if i implement the function, i cannot pass the variable down, since the state machine deals with moveStyle, not with the specific derived styles

dusk apex
#

Removing PerformJump from the equation and you'd be able to apply whatever variable/functionality you'd want to the Jump function.

livid topaz
dusk apex
#

I'm not understanding what you're saying as the child overrides the behavior of the parent.

livid topaz
#

it does, but m_JumpForce is specific to "Classic"

dusk apex
#

Sounds like a very specific design.

livid topaz
#

then what would you suggest for a more flat approach?

#

i did have jump seperated for a while but i ended up repeating code between a lot of things and it got silly

dusk apex
#

Not sure but I don't see it bringing anything new to the table other than an intermediate

livid topaz
#

ay thats a little bit of a pickle

steel elk
livid topaz
#

its not that i was avoiding the feature, its just that i didnt know of a clean way to get that hooked to a state machine so i skirted it

#

now im realizing i went the wrong way and ive got to untangle it, not sure what the best way to do that is

steel elk
#

My favorite approach is ripping the entire thing apart and asking myself why in gods name I did it this way

livid topaz
#

yup that sounds like the right way

steel elk
#

Sometimes I try to decouple things way too much as if I'm writing enterprise software that needs to be maintained for 10+ years, that my input system isn't robust enough until I could conceivably plug a Wii balance board into my FPS control system

livid topaz
#

Yeah I'm realizing that modularity is a feature of unity as a whole

#

I need not implement more

#

In fact now I realize that modularity is as simple as just having overloads jfc

steel elk
#

I make a lot of use of GetComponent respecting inheritance and what that lets you piece together

livid topaz
#

Oh so that's interesting

steel elk
#

So you can grab parent classes and interfaces with it, and implement their own unique behaviors and inspectors

livid topaz
#

Yeah I always forget I can do that

agile ice
#

i have a collision-based flag in LateUpdate that should get initialized by code executed in OnTriggerStay, and according to the unity docs on the order of execution, OnTriggerXXX gets called first beforeLateUpdate. however, during playmode, the the script is behaving as if LateUpdate gets called first before OnTriggerStay, resulting in the flag not getting initialized before LateUpdate code executed. this behavior occurs inconsistently between entering playmode, where the flag sometimes gets initialized by OnTriggerStay before its used by LateUpdate, and sometimes it doesn't. any ideas as to how to resolve this issue??

#

i want to spawn buildings, check if its colliding with any other buildings. if it is, rotate the building and disable its collision when its not colliding. if after performing the rotations and its still colliding, delete the building.

i tried implementing this by having the building spawn and detect if its colliding with another building by using OnTriggerEnter and OnTriggerExit. if the building spawns and its colliding with building object, it sets a flag isColliding = true and rotates itself as a way to result in non-collision to call OnTriggerExit that sets isColliding = false . in LateUpdate, a flag allowCollisionCheck is set to false only when isColliding is false.isColliding is also false by default and relies on OnTriggerStay to initialize it to true. So essentially, if the building spawns and its colliding with another building, OnTriggerStay is suppose to "catch" that and set isColliding = true, and if its not colliding isColliding remains false. the issue i experience with LateUpdate sometimes behaving as if it gets executed before OnTriggerStay is that since isColliding is false by default, allowCollisionCheck is set to false even when it spawns and is colliding, also preventing it from rotating itself.

#
    void LateUpdate()
    {
        //if not colliding, set meshes to visible
        if (!isColliding && !isActive)
        {
            transform.GetChild(0).gameObject.SetActive(true);
            isActive = true;
            allowCollisionCheck = false;
        }
    }

    void CheckCollision()
    {
        if (isColliding && portList.Count > 1)
        {
            //remove previous port from list
            portList.RemoveAt(0);

            //recalculate rotation and offset position of node
            Vector3 nodeEntranceOffsetPos = GenerateNode.CalculateNodeEntranceOffset(gameObject, edge.edgeExit);
            transform.position = edge.edgeExit.position + nodeEntranceOffsetPos;
        }
    }

    private void OnTriggerStay(Collider other)
    {
        if (allowCollisionCheck && other.gameObject.CompareTag("Node"))
        {
            isColliding = true;
            CheckCollision();
        }
    }
    private void OnTriggerExit(Collider other)
    {
        if (allowCollisionCheck && other.gameObject.CompareTag("Node"))
        {
            isColliding = false;
            CheckCollision();
        }
    }
dusk apex
#

Pretty sure it's simply some misunderstanding and that everything's actually going correctly in order other than conditions not being true.

#

Reminder that LateUpdate can occur more frequently than Physics events. cs LateUpdate LateUpdate OnTriggerStay - event occurred, is colliding and shift position OnTriggerExit - nothing happened yet this frame even though the object was moved LateUpdate - disabled checking LateUpdate LateUpdate OnTriggerStay - event occurred, not allowed to check OnTriggerExit - event occurred, not allowed to checkOr it could be that events occur together well before a LateUpdate frame.cs LateUpdate OnTriggerStay - event occurred, is colliding and shift position OnTriggerExit - nothing happened yet this frame even though the object was moved OnTriggerStay OnTriggerExit - event occurred, is not colliding and shift position LateUpdate - disabled checking

agile ice
#

i did not account for that LateUpdate could occur more frequently and that was my misunderstanding, so the order of execution does not matter then?

#

the debug log shows:

LateUpdate
LateUpdate - disabled checking
LateUpdate
LateUpdate
LateUpdate
LateUpdate
.
.
.

and OnTriggerStay never gets called as a result

#

the intended order should be:

OnTriggerStay - isColliding
CheckCollision - shift position
OnTriggerExit - is not colliding
LateUpdate - disabled checking
LateUpdate
LateUpdate
LateUpdate
.
.
.
hexed pecan
void basalt
#

So when I compile a bunch of unity CS files into a DLL, all of the monobehaviour classes will still be accessible as components right?

agile ice
void basalt
#

So unless you're stepping it manually using Physics.Simulate(), then it likely isn't getting called after lateupdate

#

And you might just be overlooking something

dusk apex
#

Maybe show the functions with logs and the console logs.

young bridge
#

Hey everyone. Can someone explain this to me? I'm getting an error while executing the code in editor. The error:

agile ice
# dusk apex Maybe show the functions with logs and the console logs.
void LateUpdate()
    {
        Debug.Log("LateUpdate");

        //if not colliding, set meshes to visible
        if (!isColliding && !isActive)
        {
            Debug.Log("LateUpdate - disabled checking");

            transform.GetChild(0).gameObject.SetActive(true);
            isActive = true;
            allowCollisionCheck = false;
        }
    }

    void CheckCollision()
    {
        if (isColliding && portList.Count > 1)
        {
            Debug.Log("CheckCollision - shift position");

            //remove previous port from list
            portList.RemoveAt(0);

            //recalculate rotation and offset position of node
            Vector3 nodeEntranceOffsetPos = GenerateNode.CalculateNodeEntranceOffset(gameObject, edge.edgeExit);
            transform.position = edge.edgeExit.position + nodeEntranceOffsetPos;
        }
    }

    private void OnTriggerStay(Collider other)
    {
        if (allowCollisionCheck && other.gameObject.CompareTag("Node"))
        {
            Debug.Log("OnTriggerStay - is colliding");

            isColliding = true;
            CheckCollision();
        }
    }
    private void OnTriggerExit(Collider other)
    {
        if (allowCollisionCheck && other.gameObject.CompareTag("Node"))
        {
            Debug.Log("OnTriggerExit - is not colliding");

            isColliding = false;
        }
    }
young bridge
#

The code:

agile ice
young bridge
#

if (template.IsNullOrWhitespace()) { var newscene = EditorSceneManager.CreateScene(scenePath); EditorSceneManager.SaveScene(newscene, scenePath); EditorSceneManager.CloseScene(newscene, true); }

dusk apex
# agile ice

What is the value of isColliding and isActive on initial run?

#

LateUpdate can occur before any Trigger is made if you simply start the object on top of the event trigger as Physics events do not occur every frame.

agile ice
dusk apex
#
--Start of application--
LateUpdate
LateUpdate
LateUpdate
LateUpdate
LateUpdate
OnTriggerXXX
LateUpdate
LateUpdate```
agile ice
dusk apex
#

It would immediately disable allowCollisionCheck and no further physics messages would occur.

#

Physics step would attempt to occur first, if and only if the physics frame should occur.

#

Which would be at about 50 frames per second by default.

#

Or something of the sort.

#

Whereas maybe you might be getting 200+ fps on the main loop (Update and whatnot)

#
Loop:
    fixDeltaS += deltaTime;
    RegDeltaS += deltaTime;
    while(fixDeltaS > fixRate)//Occurs first but only if the elapsed time has passed - fixed rate
        Do physics stuff
        fixDeltaS -= fixRate
    Do Update and everything else every frame.```
idle meteor
#

Hello, I'm using the Steam API and I'm having a problem inviting players.

First, I'm creating a lobby with Steamworks NET. Then, if the lobby is formed, I send a data to the lobby. Then I invite someone using the Steam interface. But when the other party accepts the request, nothing happens. I'm listening to all "GameLobbyJoinRequested_t" and "LobbyEnter_t" callbacks and printing with Debug.Log. But there is never any result.

agile ice
hexed pecan
#

If you aren't in play mode

dusk apex
#

🤷‍♂️ Time.time > Time.fixedDeltaTime (one frame)

#

It would be dirty to have a one time check. Could perhaps do so with a coroutine as well

young bridge
dusk apex
#
Coroutine:
    yield return new WaitForFixedUpdate();
    while(true)
        do stuff for the remainder of the application
        yield return new WaitForEndOfFrame();```
#

Or if that's dirty, you could inject some function into an action and call it during LateUpdate after the first frame.

toxic tiger
#

is there a standard to variable naming in Unity?

#

type_case? PascalCase?

dusk apex
#
IEnumerator Start:
    yield  return new WaitForFixedUpdate();
    DoStuffAfterOneFixedFrame = stuff;
LateUpdate:
    DoStuffAfterOneFixedFrame?.Invoke();```
#

Consider caching yields though if they aren't one time calls.

#

Or just have the script inactive for a set duration of time (or till one fixed update has occurred) then enabled it - would require the usage of a manager. cs public MonoBehaviour activateLater; IEnumerator Start: yield return new WaitForFixedUpdate(); activateLater.enabled = true; this.enabled = false;

#

Many ways to go about this.

#

Reminder that a coroutine would be disabled once the component becomes disabled or object inactive.

#

Another script observing this script would be require for the last suggestion made and decoupling the physics interaction with late update interaction - you'd probably want the physics stuff to still be able to have occurred.

toxic tiger
#

is it camel case?

toxic tiger
#

alright thanks

#

also I get this is just a warning but how could I make it "efficient"?

dusk apex
toxic tiger
#

new Vector3(x, 0, z) * (Time.deltaTime * 10);

#

this is the solution it gives, isn't this not correct?

dusk apex
#

Ideally scalars should be operated upon first then applied to a Vector

toxic tiger
#

shouldnt deltatime be multipled after or does it not matter

dusk apex
agile ice
# dusk apex Or just have the script inactive for a set duration of time (or till one fixed u...

thanks for the coroutine method, i understood this as: implement a coroutine to wait for FixedUpdate to allow for OnTriggerStay to get called first before LateUpdate. then i realized i didnt need LateUpdate, but could instead run the code that was in LateUpdate, in the coroutine instead. and then have the coroutine call itself as needed if collision is still detected. https://gdl.space/efihajahar.cpp

dusk apex
somber nacelle
dusk apex
dusk apex
dusk apex
agile ice
#

thx ^^

steep scarab
#

Hey guys, sorry for duplicate question but I couldn't seem to find an answer in #💻┃code-beginner. I seem to be having some trouble with Quaternion.FromToRotation. I'm making a tank turret type thing where I control the guns elevation and the turret rings rotation separately, and as you can see here while the guns elevation IS correctly facing the target, the turret rings rotation is however not. Here is the code I wrote:

    {
        newQuat = Quaternion.FromToRotation(transform.up, (targTransf.position - transform.position).normalized);

        Debug.Log(newQuat.eulerAngles);

        Debug.DrawRay(transform.position, newQuat * Vector3.forward);

        setRot(newQuat.eulerAngles.y, newQuat.eulerAngles.x);
    }

    private void setRot(float x, float y)
    {
        gunBase.localRotation = Quaternion.Euler(0, x, 0);
        gunBarrel.localRotation = Quaternion.Euler(y, 0, 0);
    }

The issue seems to be with "newQuat" and Quaternion.FromToRotation, as debug.log shows that the eulerangle is correctly adjusting along the Y axis, however the x axis is just not changing, with its value never exceeding a value of 24-ish. Does anyone know what might be up? I can't find much tutorials involving Quaternion.FromToRotation at all, and from what I've read there shouldn't be any reason its not returning the correct "horizontal" value... unless maybe I'm understanding the way it works incorrectly? I was wondering if .FromToRotation accounts for the z axis but I dont see why it wouldn't... any help is really appreciated regardless.

glad solstice
#

hey question,
im making a mod for a game (dw it supports modding)
and i want to add pathfinding to a object, i have it so the object can move towards a player normally using Vector3.MoveTowards but obviously it doesnt detect objects stopping it
i want to know if there is any pathfinding solutions that can work in runtime without baking or placing nodes and work dynamically as objects might be places in it way
preferably i would like to avoid adding components to the floor such as navmeshsurface as i dont know the name of the floor
not sure if it makes sense
im making a goose in a game follow people if you are interested, usually the goose is just a object you can pickup but i wanna make it able to move around the world even though i didnt make the world

#

im not fully sure of the untiy engine version but its old

#

2019.4.xxf1 or something

steep scarab
glad solstice
#

figured

steep scarab
#

and a navmeshagent

glad solstice
#

was just wondering if there was alternatives out there but nvm ig xD

uneven summit
#

does anyone here have experience with the pixel crushers dialogue system plugin?

uneven summit
#

mb

lethal crag
#

I'm making a top down 2D mini-golf game for fun, what would be the best way to 1. have the ball bounce off walls like it should (without just sliding against the wall) and 2. have a sort of friction (I have a rigidbody2D but its top down so it doesnt do much

gray zephyr
#

Hello everyone 😁
I just wanted to ask something very general, tell me if I'm in the wrong channel

is it bad practice to have multiple scripts on one GameObject, all toggled on/off by a single, larger controller script?
all of my scripts use Update calls so I prefer to avoid them all running at once

gray zephyr
#

mmm

#

hmmm

#

thank you :3

glad solstice
# steep scarab I mean if you want "pathfinding" in unity ur gonna need a navmesh

So I need to use navmesh
But im using it in a mod won't needs to be runtime so I can't bake anything it
I'm also using a older version of unity 2019
Is there a way to have the agent find a usable surface? I have the names of the floor objects but I can't manage to assign then a navmesh for the agent also going bed now so if you have an answer please @ me thx

ionic adder
#

I'm having a hard time grasping why 5 % 6 (as an example) evaluates as 5. I understand the modulo operator when the first parameter is larger. Like it makes sense to me that 6 % 5 evaluates as 1, since 5 "fits" into 6, with 1 remaining. But I'm just not understanding the mathematics behind it when the first parameter is smaller. If someone would be able to explain it to me, I'd be very grateful.

somber nacelle
#

it's just a remainder operator. did you ever learn long division in grade school?

#

it's the same concept as a remainder in that

#

5 cannot be evenly divided by 6, so the result of the division is 0 with a remainder of 5

ionic adder
#

ahh, thanks. that made it click for me.

wild nebula
#

Anyone know how to convert int to generic Enum?
In known Enum, you can go like this:

(MyEnum)index

But on generics, I can't.

Class<T> where T : struct, Enum

(T)index //Error
quaint rock
#

the enum needs to be a concrete type you cast to

sharp flame
#

whats the difference between

public Foo FooManager => FindObjectOfType<Foo>();

And

Awake(){
FooManager = FindObjectOfType<Foo>();
}
Is there a negative between using the first?

quaint rock
sharp flame
#

I see and

private bar
public Foo FooManager
{
get => bar
}

And

Awake(){
bar= FindObjectOfType<Foo>();
}

in this case FooManager will get the reference to bar right?

#

So basically something like

private ToggleAndFadeUIObject _toggleAndFadeUIObject => GetComponent<ToggleAndFadeUIObject>();

is bad practice because it calls the GetComponent everytime

#

Thanks for the help!

quaint rock
#

yes

#

generally would avoid it in 1 of 2 ways, just click and drag the reference in directly

#

or do the GetComponent in awake

#

and just expose it publically later with a getter

#

you can also avoid the backing field in this case you want

public Foo FooManager {get; private set;}
#

then you can set it in Awake

#

but things can still publically read it but not set it

sharp flame
#

Gotcha thank you!

quaint rock
#
public Foo FooManager {get; private set;}

private void Awake(){
    FooManager = FindObjectOfType<Foo>();
}
sharp flame
#

was so hoping it was just a quicker syntax to lambda it 😄

quaint rock
#

the lambda syntax is the same as if it was a function

sharp flame
#

makes sense

#

Thank you!

quaint rock
#

well better wording is getters and setters are just functions disguised as a field, the logic in both of them runs when accessed not at initialization

lethal crag
tiny delta
#

Anyone got tips for readably getting the corners of a square? I'm a master of overthinking practicing my craft.
Attempt 1:

corners[1] = new Vector2(posX + sideLength / 2, posY + sideLength / 2); // Top Right
corners[2] = new Vector2(posX + sideLength / 2, posY - sideLength / 2); // Bottom Right
corners[3] = new Vector2(posX - sideLength / 2, posY - sideLength / 2); // Bottom Left```
Attempt 2:
```string[] cornerDirection = new string[4] { "-+", "++", "+-", "--" }; // Starting in top left, continues clockwise
Vector2[] corners = new Vector2[4];
for(var i = 0; i < sideLength; i++)
{
    float sideX = 0f;
    float sideY = 0f;

    if (cornerDirection[i][1] == '-')
        sideX = posX - (sideLength / 2);
    else if (cornerDirection[i][1] == '+')
        sideX = posX + (sideLength / 2);

    if (cornerDirection[i][2] == '-')
        sideY = posY - (sideLength / 2);
    else if (cornerDirection[i][1] == '+')
        sideY = posY + (sideLength / 2);

    corners[i] = new Vector2(sideX, sideY);
}```
#

I'm sure there's a smarter way of doing this that I'm just not seeing

mossy snow
#

what's wrong with option 1? don't be clever, make it readable

somber nacelle
#

option 1 has some math issues (check your signs 😉 ) but is otherwise fine

#

ah wait, looks like you may have edited the issues i was referring to

tiny delta
#

It just feels wrong having four nearly identical lines in a row

somber nacelle
#

alternatively, you could store (1,1),(-1,-1),(-1,1),and(1,-1) in an array then loop over that array and multiply that by the half extents

tiny delta
#

ooh that's not a half bad idea

#

and sounds much more readable

#

(and harder to mess up the signs for)

twin geyser
#

I downloaded the .NET core sdk

#

Still says you have to download it or retarget it

somber nacelle
#

did you restart after installing it?

twin geyser
#

Let me try

tiny delta
twin geyser
swift falcon
#

Is there anyway to cut down on code for a variable kind fighting system?

like if you're in the air vs if you have the enemy grabbed

Im thinking like state machines could do this but I'd like to know if theres any other ways

mild coyote
#

animation state machine XD
but it would be a pain to debug I think

tepid jewel
#

I am not really sure if this is beginner, general or advanced but feels like it is more general. I have a unity scene with mapbox and a api from where I get coordinates. I make the coordinates into unity world positions and place the green markers where they are. I now want to create "links" between the points by using cylinders. I first tried to use the linerenderer but it was buggy (only showing from certain viewing angles) and preformance was bad. I have tried a couple of things but can't really figure out how to calulate the rotation and scale for the length. The cylinder prefab is in a empty object wrapper that makes it lay down on the side, and raises it up as well as setting the origin to the end of the cylinder.

#
var pPos = _map.GeoToWorldPosition(p.Prev.Pos, true);
var vec = (pPos - pos).normalized;
linker.transform.rotation = Quaternion.LookRotation(vec);
linker.transform.localScale = new Vector3(vec.magnitude, 1, 1);
#

prefab model where the origin is shown

hexed pecan
#

And use Z scale instead of X

#

Alternatively you can do what you currently do but apply some corrective rotation afterwards with transform.Rotate for example.

tepid jewel
#

Alright, will do that, thank you :)

tepid jewel
#

the direction works now, thank you but I think my scale calculation is wrong.

#

I removed the .normalized because with it the size only got the be 1

simple edge
#

B-A = the offset between two vector points
Grab the magnitude of this offset, which is the length
Set the cylinder length with that
There shouldn't really be any more to it

#

If that doesn't work, check if your cylinder model is "one unity meter", by comparing it to a cube

tepid jewel
#
var pPos = _map.GeoToWorldPosition(p.Prev.Pos, true);
var vec = pPos - pos;
linker.transform.rotation = Quaternion.LookRotation(vec);
linker.transform.localScale = new Vector3(1, 1, vec.magnitude);
#

so this should work?

simple edge
#

It looks alright from a quick glance, can't you test it?

tepid jewel
tepid jewel
tepid jewel
tepid jewel
# tepid jewel

but I have never modified the cyilders scale, is the cylinder by default "longer"?

simple edge
vestal crest
#

@earnest epoch hey, i still have been working on that i figured something but it doesnt work well. What i did is create a method and make it menu item. what method is do change a bool. so i press start from loading screen menu item it changes a bool to true in datamanager (static class, player prefs). but theres a thing when i change that bool to true and press play it does not start from loading scene, but when i stopped playing and press play again it starts from loading scene. in short player prefs bool work after first play and i dont know why

tepid jewel
cold onyx
#

Does anyone know why I'm getting different timings on my Debug.Logs for this code?

foreach (var spikeTrap in Globals.Instance.spikeTrapList) {
    spikeTrap.InitializeTrap();
}

I'm calling this during the Start() function of my game manager script. spikeTrap.InitializeTrap() simply displays a Debug.Log message saying that it started. For some reason I'm getting different timings on these messages though... Shouldn't they all happen in the same frame?

wicked scroll
mellow sigil
#

What are you logging? Even if things happen in the same frame that doesn't mean they happen at the same time

cold onyx
#

Long story short, I have timers that repeat once every 10 seconds, causing these Spike traps to activate. The problem is that some of the traps aren't in sync with the others. They're literally all running at the same exact time though so I'm lost...

thin aurora
#

Is it a coroutine?

wicked scroll
#

not much we can do for you though

#

add a lot of very verbose logging or step through with your debugger and make sure the code is being run like you think it is (cause it isn't)

cold onyx
#

I'm using a custom timer class, I'll try to see if one single timer managing all of them at once will help. Regardless, they start at different times despite only relying on the Start() method for the initialization process.

wicked scroll
#

do you have objects coming alive later than others?

#

start is just for that monobehavior but if you don't instantiate it until later, it won't run start until then

cold onyx
#

They're all preplaced in the scene

#

But I am instantiating other objects at the same time

thin aurora
#

My point is that using a coroutine for it is unreliable

#

So if each trap uses their own timer instance they are not guaranteed to run at the same speed

#

Because yield return new WaitForSeconds(5) for example will never wait exactly 5 seconds

#

So if each trap has their own timer instance and it works with coroutines, that's atleast part of the problem

steep drift
#

TLDR; "a custom timer class" unfortunately isn't super helpful in narrowing down the problem vs. talking about what that timer is rooted in.

cold onyx
#

It's not coroutine based but maybe it shares the same issue:

       private void Update() {
            for (int i = 0; i < timerList.Count; i++) {
                timerList[i].UpdateTimer();
            }
        }

^ That's part of a single TimerManager class which contains a List of Timer objects. Each Timer does this:

       public void UpdateTimer() {
            if (isPaused) { return; }

            timeElapsed += Time.deltaTime;
            if (timeElapsed >= timeNeeded) {
                if (isRepeating) {
                    callbackAction.Invoke();
                    timeElapsed = 0;
                } else {
                    callbackAction.Invoke();
                    Cancel();
                }
            }
        }
thin aurora
#

Because unlike a coroutine's instruction, time.DeltaTime is very reliable

#

Atleast we can narrow the problem down

wicked scroll
#

well do you ever pause any of em?

cold onyx
steep drift
#

All traps have callbacks registered, which is where they do their thing? Or does a central manager have a callback registered which in turn asks each trap to do their thing?

cold onyx
#

Currently I've given each trap it's own Timer with it's own callback

#

But I'm about to test one single Timer to manage all of them

#

I still don't understand why they'd be out of sync from the start though... I'm not even using the Timers there

steep drift
#

If you spawn the traps in update.

#

Or otherwise have them register there.

#

That would run the risk of having the timer for a given trap run one frame early or late vs. others.

plain coyote
#

does a scene in unity contain modification or just a change in the objects?
so if saved a scene, and then I modified the scripts, I assume the scene that I saved before will contain the new code
right?

steep drift
#

Scripts are not stored in scenes, no. However changed serialised values are.

#

So if you serialise value A with a default value of 5 specified in script, change the value to 7 in the inspector of an object in the scene, and then change the default value in script to 14 then the value in the scene will still be 7.

#

Same holds true for instances on prefabs ofc.

#

Default values for non-serialised variables do not stick in the same way. If B is a non-serialised variable on the same script with a default value of 5, you then add an instance to a GO in a scene and change the script default value from 5 to 14, then the value will be 14.

plain coyote
#

Thanks

steep drift
#

No problem 🙂 Worth noting that if you're running without sound for personal preference, it is worthwhile deciding on one day per week or so being your sound-on day. Many, many projects have slid because people developed without sound and then discovered an ocean of audio issues just before some milestone - when they finally turned it back on 😉

sonic edge
#

Hello, how is it possible to access to the script of a GameObject with a variable name (because I have severals enemies with their own script) ?

thin aurora
thin aurora
# sonic edge they already exist

If you only need to reference a single enemy, you could just assign them to a [SerializeField] private Enemy _enemy; field. Alternatively have a manager keep track of your enemies by having it collect all existing enemies when your game starts, and continue filling/removing from that list when you add/remove enemies in your scene. You then just iterate that list.

#

Shitty solution is using any of Unity's find methods, which I do not recommend.

thin kernel
#

Hello. How to make a BoxCast in 3d world with ui element, like image? I know about raycast with (Camera.main.ScreenPointToRay(Input.mousePosition)), so I do have the position and direction. Now I need to make my cast the same size as ui element, any ideas how to do that?

#

So, basically, I want to drag an image on the screen and get all 3D objects that behind it.

granite nimbus
#

Is it technically impossible to have all vertices in a mesh be unique? what I mean is, a cube consists of 8 vertices, but technically a generic unity's cube is using 24 vertices. So each quad is using its own set of vertices. is it possible to make it use 8 vertices? and if yes, is it applicable to more complex meshes?
for example, I create a mesh that contains 16x16 quads (looks like a plane), and if all vertices were unique, it would use only 289 (17*17) vertices, while in fact its using about 1500

tepid jewel
#

In unity I have a mapbox 3d map and when I am zoomed out alot where a city is pretty much covered by a small area I don't need it to render every single point I have there. Is there some efficient way to deactiave 3d objects (prefabs) that have the same positions or the positions are very close, lets says within 0.1 unitys of each other?

late lion
spark flower
#

hey guys

#

so i have a vector3 which has only its X and Z set, Y is set to 0

#

i use this vector for velocity

#

but i need to get the direction from this vector

#

so i need to get Y

late lion
trim schooner
#

it is against the rules to crosspost, delete it

granite nimbus
late lion
granite nimbus
late lion
#

But technically you could also calculate the normals in the shader manually or encode the three normals into other vertex attributes and unpack them in the shader.

granite nimbus
#

I may not need correct normals in some cases?

languid lichen
#

Hey guys! I have a UI popup containing 9 buttons, and I have this initial foreach loop in void Start() that basically says “wait until the button is clicked” by adding a listener (Screenshot 1). This is handled by HandleButtonClick(). Here, whenever the button is clicked, I have the bool buttonIsClicked set to true (screenshot 2)

In a connected script that references this script^^ (aka line 68), for some reason this isn’t being called/reached. I put Debug.Log’s, and only the outer “First if statement reached” is being printed, and not this inner one. I checked that the buttonIsClicked bool is true, which should progress to this inner one.

Any feedback/comments would be greatly appreciated!

late lion
granite nimbus
thick heron
#

button not working

#

pls help

#

@plush basalt pls help

#

@heady marten why no work

muted idol
#

guys how to set default value for struct like Vector3 in a public method like this?

public static void MyMethod(this CharacterController controller, Vector3 offset = new Vector3(-.5f, 0, -.5f)) // This will give error "Default parameter value for must be a compile-time constant"
muted idol
mental rover
vestal crest
#

is there a way to cast a Scene as SceneAsset

#

(SceneAsset)EditorSceneManager.GetSceneByBuildIndex(0)

#

this is what i want to achieve

#

i think there s no way

#

ahhahahah 😄

#

    static EnterPlayModeSceneChange()
    {
        SceneAsset loadingScene = AssetDatabase.LoadAssetAtPath<SceneAsset>(loadingScenePath);

        if (loadingScene == null)
        {
            Debug.LogWarning("There is no LoadingScene or not found!");

            EditorSceneManager.playModeStartScene =
                AssetDatabase.LoadAssetAtPath<SceneAsset>(EditorSceneManager.GetActiveScene().path);

            return;
        }

        EditorSceneManager.playModeStartScene = loadingScene;
    }```
#

my co worker said you can do this better instead of getting asset in assetdatabase so i gave it a try but

#

i have no idea how to make this better

languid lichen
# mental rover well, you've narrowed it down pretty well - there's pretty much only one thing i...

thanks for your response! i'm trying a different approach. Instead of calling the StartCoroutine under line 72 in the second script (called InterfacePivot.cs), I thought maybe it has something to do with the "ordering" of when these methods might be called. When my gameobject is instantiated, it is immediately tagged with "TaggedSelectionInterfaceInstance"

In my first script (called SelectionInterface.cs), I find that instantiated gameobject by tag. However, I'm getting a 'Object reference not set to an instance of the object.' on line 154

I've previously defined interfaceScriptInstance in the third screenshot here, so I'm not quite sure where I went wrong.

mental rover
languid lichen
#

hmm gotcha, what other alternatives would there be? quick google search says its bad for performance, but realistically im not too worried about that

mental rover
#

it's not clear to me why you're mixing buttons and triggers here, what are you trying to do?

vagrant blade
languid lichen
#

So basically I'm around this environment. When I collide into this empty gameobject (with the InterfacePivot.cs script attached)... I instantiate this canvas/UI with these buttons. (with the SelectionInterface.cs script attached)

When I click any of these buttons (buttonIsClicked bool), I start this coroutine (AccessMeshRendererAndShowFeedback)

mental rover
#

right.. but you're checking for whether the button is pressed immediately in OnTriggerEnter? that will of course be false

languid lichen
#

But would that(?) be a separate issue than the one I'm experiencing now, aka the object reference not being set to an instance

mental rover
#

OnTriggerEnter wont pause in the middle of its execution and wait for a button to be pressed

languid lichen
mental rover
#

if you're essentially instantiating a prefab that contains your buttons and interface script, you can set them up with references in the inspector directly
alternatively GetComponent will work, but you need to make sure it's on the right object in your hierarchy

tight fjord
#

Any idea how to make a tictactoe game, without wasting a bunch of space with a very larger number of if statements?

#

(Player vs AI)

sonic stream
#

so coming here again for my path-finding stuff,i am looking for help again,to try to optimise the amount of nodes to be searched,I tried doing a simple calculation which worked perfectly in another try,now i am trying to apply it to grid generation,but it gives an InvalidOperation Error (ArgumentRange error when burst compilied),any idea why?


        //Doesn't work in a backwards way
        Vector2Int gridSizeVector = Vector2Int.CeilToInt(endPosition - startPosition) * 2;
        int2 gridSize = new int2(gridSizeVector.x, gridSizeVector.y);
        //Works in a backwards way,but sometimes bugs out
        int2 gridSize2 = Mathf.RoundToInt(Vector2.Distance(startPosition,endPosition)) * 2;

the grid creation stuff

#
int2 GetInt2FromVector2(Vector2 position)
        {
            int x = Mathf.FloorToInt((((position - startPosition).x) + ((gridSize.x / 2f)) / offset));
            int y = Mathf.FloorToInt((((position - startPosition).y) + ((gridSize.y / 2f)) / offset));
            return new int2(x,y);
        }

the stuff that converts from world to grid

lucid valley
#
math.floorToInt()
sonic stream
lucid valley
#

Whats the exact burst error? And show the code which the error says it can't compile

sonic stream
#

should have specificed that

sonic stream
sonic stream
lucid valley
#

Can you show the PathFinding.PathFindJob

#

and if it's not burst compiled does the error give better info? (if it still happens)

sonic stream
sonic stream
lucid valley
tepid jewel
#

In unity I have a mapbox 3d map and when I am zoomed out alot where a city is pretty much covered by a small area I don't need it to render every single point I have there. Is there some efficient way to deactiave 3d objects (prefabs) that have the same positions or the positions are very close, lets says within 0.1 unitys of each other?

sonic stream
lucid valley
#

try adding a log to the while loop and count how many loops it's done?

#
var count = 0;

try
{
                while (currentNode.cameFromNodeIndex != -1)
                {
                    count++;
                    PathNode cameFromNode = pathNodeArray[currentNode.cameFromNodeIndex];
                    path.Add(new int2(cameFromNode.x, cameFromNode.y));
                    currentNode = cameFromNode;
                }
}
catch(Exception e)
{
    Debug.LogError($"Looped {count} times!");
    Debug.LogError(e.ToString());
}
#

something like that

lucid valley
#

uh, i guess you can just log the count each time in the while instead

#
                var count = 0;
                while (currentNode.cameFromNodeIndex != -1)
                {
                    count++;
                    Debug.LogError($"Looped {count} times!");

                    PathNode cameFromNode = pathNodeArray[currentNode.cameFromNodeIndex];
                    path.Add(new int2(cameFromNode.x, cameFromNode.y));
                    currentNode = cameFromNode;
                }
#

but i am pretty sure this while loop just isnt stopping

sonic stream
#

ok

#

also i sorta found something that did somewhat work abit

#

i basically checked if the end node is smaller than 1 and made it so that it would act as the origin instead of the direction in the gridSize calculation

sonic stream
lucid valley
#

thats why i wanted to avoid it with the try catch

lucid valley
#

the editor is probably fully frozen so you'll need to path to it manually (or you can press a button next to the console to open it if it wasnt)

#

for windows it's: %LOCALAPPDATA%\Unity\Editor\Editor.log

lucid valley
#

you use this to calculate the end node index int endNodeIndex = CalculateIndex(endPosition.x, endPosition.y, gridSize.x);

#

but you are checking this in the while currentNode.cameFromNodeIndex != -1

#

it doesnt seem like the end node will be ever be -1?

sonic stream
lucid valley
#
            if (endNode.cameFromNodeIndex == -1)
            {
                //Couldn't find a path!
                return new NativeList<int2>(Allocator.Temp);
            }
#

you are doing this check before the while loop

#

what you want is this

#
while (currentNode.cameFromNodeIndex != endNode.index)
#

or maybe

#
while (currentNode.index != endNode.index)
#

probably that one

#

wait sorry

#

i forgot that this bit goes backwards when finding the path from the nodes

#

so you'd want to check for the starting position index

#

which in theory should have this be true currentNode.cameFromNodeIndex != -1

#

huh

#

i guess you could try sending in the starting index as a parameter (or the node) and checking that instead

#
while (currentNode.index != startingNode.index)```
sonic stream
lucid valley
sonic stream
sonic stream
lucid valley
# sonic stream so i just replace endNode with startNode,but what else do i replace?
private NativeList<int2> CalculatePath(NativeArray<PathNode> pathNodeArray, PathNode endNode, PathNode startNode)
        {
            if (endNode.cameFromNodeIndex == -1)
            {
                //Couldn't find a path!
                return new NativeList<int2>(Allocator.Temp);
            }
            else
            {
                //Found a path
                NativeList<int2> path = new NativeList<int2>(Allocator.Temp);
                path.Add(new int2(endNode.x, endNode.y));
 
                PathNode currentNode = endNode;
                while (currentNode.index != startNode.index)
                {
                    PathNode cameFromNode = pathNodeArray[currentNode.cameFromNodeIndex];
                    path.Add(new int2(cameFromNode.x, cameFromNode.y));
                    currentNode = cameFromNode;
                }
 
                return path;
            }
 
        }
lucid valley
sonic stream
sonic stream
lucid valley
#

do you know how to use a debugger?

#

All i can suggest now is to use breakpoints and see whats happening during the loop

sonic stream
sonic stream
#

@lucid valley does this help?

lucid valley
#

55428584 length

#

try making a small grid then inspect pathNodeArray and try to work out the path backwards yourself using the cameFromNodeIndex

#

Using the same logic the while uses

simple ridge
#

Hi everyone, I am looking into Unity Lobbys and I was wondering what is the correct way to set up a lobby in the sense that there doesn't need to be a specific host. By this I mean I would like for all players to just press a join button, and one of them automatically making a lobby that the others join seamlessly, without the need for a second seperate button for someone to click to host a game.

I've been reading the docs and they don't really seem to cover this, quick join is kind of what I want, however that doesn't seem to mention anything about creating a lobby if non are avaialbe. Would the solution be to have all players just create a lobby and search for one at the same time? Any pointers on what would be good practice would be apreacated

sonic stream
lucid valley
#

and follow the code through using breakpoints

sonic stream
lucid valley
#

i guess you could say it is "normalised" to 0, 0

#

that case should've been caught as a no path found

#

i'm not sure how it's ending up to that while loop

sonic stream
#

yeah

lucid valley
#

you turn it back into your world coord after the path has been found using GetPositionFromInt2

sonic stream
#

but is there a way to make it so that the negative values can work?

lucid valley
#

actually thats just a float

#

humm

sonic stream
lucid valley
# sonic stream it is the offset between nodes
public Vector2[] FindPath(Vector2 startPosition, Vector2 endPosition, float offset)
{
        int2 gridSize = Mathf.RoundToInt(Vector2.Distance(startPosition, endPosition)) * 2;

        int2 gridOffset = int2.zero;
        
        gridOffset.x = startPosition.x < 0 ? Mathf.CeilToInt(-startPosition.x) : 0;
        gridOffset.x = endPosition.x < 0 && gridOffset.x > endPosition.x ? Mathf.CeilToInt(-endPosition.x) : gridOffset.x;

        gridOffset.y = startPosition.y < 0 ? Mathf.CeilToInt(-startPosition.y) : 0;
        gridOffset.y = endPosition.y < 0 && gridOffset.y > endPosition.y ? Mathf.CeilToInt(-endPosition.y) : gridOffset.y;

        //Other logic
{
#

that should get you an offset so that the start and end are always in positive space

sonic stream
lucid valley
#
        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)));
            x += gridOffset.x
            y += gridOffset.y

            return new int2(x,y);
        }
lucid valley
#

You cant have negative distance

#

and then in this function you'll want to take away the grid offset

#
        private float2 GetPositionFromInt2(int2 value)
        {
            return (new float2(value + origin) * offset) - ((gridSize.x / 2f) * offset);
        }
#

so you'll need to send it into the job

sonic stream
sonic stream
lucid valley
#
        private float2 GetPositionFromInt2(int2 value, int2 gridOffset)
        {
            var position = (new float2(value + origin) * offset) - ((gridSize.x / 2f) * offset);
            position.x -= gridOffset.x;
            position.y -= gridOffset.y;

            return position;
        }
sonic stream
#

you mean the gridOffset?

lucid valley
#

yeah

sonic stream
#

should i cast,round or floor it?

lucid valley
formal quest
#

I'm trying to understand bitmask. I'm using EditorGUILayout.MaskField which gives me an int result. If I have a List<int> of different results, how can I use LINQ to get only the ones from the list that contain a specific string option?

sonic stream
lucid valley
#

and you'll have to cast it to int after

#

or make an extension method to do it for you

lucid valley
sonic stream
sonic stream
#
public int2 gridSize;
        public int2 startPosition;
        public int2 endPosition;
        public float2 origin;
        public int2 gridOffset;
        public float offset;
        public bool canMoveDiagonal;
        public NativeList<float2> resultPath;

basically put it here

#

@lucid valley it seems i forgot to assign it in the Job Constructor,but it still has the same result

mellow rain
#

Does anyone know how to make a character who moves using Vector based motion to not go flying off slopes? I want my character to stay on the floor and not go flying

frosty berry
soft shard
# mellow rain Does anyone know how to make a character who moves using Vector based motion to ...

Assuming you are using a rigidbody + collider setup instead of a CharacterController component, you will want to apply a constant downward force to essentially act as gravity for your rigidbody - you can do the same with a CharacterController, theres just less flexibility as you only have 1 way of applying motion, and there may be some cases where going up-hill or something like a double-jump or swimming, etc that you may want to disable or reduce your gravity for - if you need help with movement, you could search up tutorials for a rigidbody based character controller, here is one good example: https://www.youtube.com/watch?v=1LtePgzeqjQ

In this tutorial, you will learn how to make a Rigidbody - based player controller using Unity's new input system.

▶ Play video
bitter saffron
#

Is there a way to send a friend the game I build for IOS via e-mail or so? Do I need to publish it on the appstore?

frosty berry
#

cuz they don't allow u to download apks

#

or any app

bitter saffron
#

man apple is some .... :/

simple ridge
#

Hi everyone, I was wondering if there was a way to change the anonymous sign in ID on a device, I'm trying to use Unity Lobby and would like to test some code on two editors using ParrelSync but when using AuthenticationService.Instance.SignInAnonymouslyAsync I receive the same playerID for both editors, because of that when I try to join a lobby it throws an error saying that I already am connected.

Is there a way around this? I've seen you can sign in with specific Google, Apple and Steam account access ID's but I'd rather not log in to my own personal accounts for a work project. Or can you just use fake ID's with these?

hard sparrow
#

Is it smart to want something editable through the editor but static during runtime?

#

I was thinking a readonly ColorLibrary which has all the colors everything will use

#

also is even possible to having something serialized through the editor but static during runtime?

dim spindle
#

Yeah thats most things in unity, no?

hard sparrow
#

Well I made it a singleton but it won't let me reference the 'non-static' colors

dim spindle
#

[SerializeField] private int real;

dim spindle
#

Object.instace.color

delicate olive
#

Does anyone here know how to modify a UI TextMeshPro's RectTransform position at runtime?

hard sparrow
dim spindle
#

Lol

hard sparrow
#

no words

simple ridge
vague slate
#

so. I have Vector2 value. up/down/left/right thingy
But it's local.
I also have a vector2 that indicates custom up.
So I need to somehow calculate absolute up/down/left/right values.
Any ideas?

vague slate
#

no transforms where I am

#

I need it with Vectors

leaden ice
#

Matrix4x4

vague slate
#

could you elaborate?

leaden ice
#

actuall sorry that's more than you need

#

you just need a quaternion

#

someQuaternion * someVector rotates the vector by the rotation indicated by the quaternion

#

you just need to rotate the vector to whatever orientation makes sense

#

you'll need to elaborate on what "custom up" means

#

and "absolute up/down/left/right"

#

for example let's say you want to convert your x/y input to x/z

vague slate
#

so, I have a Vector2, which would equal one of possible points on this red circle. I also have green vector. What I need: is to rotate circle to the point, it's up equals green vector

leaden ice
vague slate
#

basically, what I have is blue vector, what I need yellow

leaden ice
#

I mean yellow is literally just greenVector.normalized

#

not sure how blue is related

#

if you want the rotation from blue to yellow, that's what my quaternion thing above will give you

vague slate
#

it can be any direction

vague slate
#

hmm

leaden ice
#

Quaternion rotation = Quaternion.FromToRotation(blueVector, greenVector);

#

now with the blue instead of Vector3.up

#

And yellow is still greenVector.normalized

vague slate
#

I'm a bit confused why I need quaternion here, since I need Vector

#

or you mean I then should obtain euler from it?

leaden ice
#

If you just want the yellow vector, it's greenVector.normalized

vague slate
#

Blue vector is example

#

simple example

#

hold on

#

I'll make another

leaden ice
#

Maybe explaining your actual issue will help because this is probably oversimplified

leaden ice
#

Quaternion is already a rotation representation, and a much more useful one than euler angles

vague slate
#

original would be blue, result would be yellow

leaden ice
#

what is green

#

I don't understand

vague slate
#

angle between them would equal angle between normal up and green vector

leaden ice
#

can you explain the actual thing you're trying to do

leaden ice
vague slate
#

I have input from gamepad stick (blue vector), I need to make it so when stick looks up, character also looks up. But since camera angle does not match values from raw input, I need to adjust it to camera->character vector

#

basically, camera can look to south, while raw input gives me north. Thus character must look south, where camera looks

leaden ice
#

Is this a 2d game? 3d game? Top down?

#

what's the camera angle

vague slate
#

3d, where camera acts more like in a platformer

leaden ice
#

like free rotating?

#

Like mario odyssey?

vague slate
#

I haven't played it 😅

leaden ice
#

any 3d mario game

vague slate
#

basically

#

if stick goes north

#

I need to see back of character

leaden ice
#

that's all you're asking

vague slate
#

if stick goes south - I want to see face

leaden ice
#
Vector3 cameraForward = myCamera.transform.forward;
Vector3 projected = Vector3.ProjectOnPlane(cameraForward, Vector3.up).normalized;

inputVector = Quaternion.LookRotation(projected) * inputVector;```
frigid wadi
#

can someone help please

leaden ice
#

I was getting confused by the whole "looking up" thing. @vague slate

leaden ice
frigid wadi
#

they are installed though

#

whats an sdk manager

#

im new

leaden ice
frigid wadi
#

its for vr

leaden ice
#

this is an Android problem

frigid wadi
#

oh ok

leaden ice
#

nothing to do with VR

frigid wadi
#

but im making it for quest lol

#

so its android

leaden ice
frigid wadi
#

oh

#

ok

vague slate
vague slate
leaden ice
dense cloud
#

question about the line with Instantiate(), why is the cast labelled as redundant?
I'm following a book, and it said that without the typecast, it will spawn a Object not a GameObject

leaden ice
vague slate
#

oh, so if I multiply quaternion with vector that would equal to rotated vector

#

I see

leaden ice
#

you passed in GameObject so it returns GameObject

dense cloud
#

ah, so this is line is wrong?

leaden ice
#

actually I think it used to be that way

#

it's ooutdated

#

Hasn't been that way in like 6+ years

dense cloud
#

not sure how good it is tho

leaden ice
#

books are always awful for software IMO

#

inevitably outdated

dim spindle
dense cloud
#

oh yea that's true

vague slate
dense cloud
#

I didn't like video tutorials, so I settled with books

#

I think I'll try hybrid, some tutorials and books

#

but thanks for the help

#

I think I'll stick with this book till the end, and try to make simple stuff on my own

#

I did make a game that followed a tutorial from start to finish, and did learn the basic layout of Unity

hollow kernel
dense cloud
hollow kernel
#

ok cool thank you

#

but why does my issue happen

#

its very weird and it always happens

#

like everytime it hits the corner

wide fiber
#
 void Update()
    {
        if (Input.GetKeyDown(KeyCode.T))
        {
            waveIndex++;
            hasSpawned = true;
        }
        SwitchingSpawner(hasSpawned == true);
    }

    void SwitchingSpawner(bool spawned)
    {
        switch (waveIndex && spawned) <=== this line got error
        {
            case 1:
               Instantiate(waveSpawner[0]);
                hasSpawned = false;
                break;

hi sorry. I'm trying something here haha but why is that line got error? it says && cant be applied to bool? but i thought that worked

simple ridge
#

What are you trying to do?

#

A switch statement will compare the input with all cases below it, for example wave Index looks like it is an integer, so case 1 works when wave Index on its own is an input.
With the && however you are saying the input for the switch is a boolean, and the boolean is made up of the conditions of (waveIndex and spawned), which means you trying to compare if waveIndex is a boolean value.

#

The error can be seen a bit better if you think of it as an if statement
if (waveIndex && spawned)
is equivelent to saying
if (number && true / false)
I don't believe C# lets you do Boolean logic directly on ints, as if (4) doesn't really mean anything.

#

If you are trying to do a conditional for if the object has spawned then what wave is it, then you just need to put the switch in a if statement

if (spawned)
{
    switch (waveIndex)
    {
      ....
    }
}
simple ridge
wide fiber
simple ridge
#

No trouble, hope it works ^-^

lethal crag
#

Im making a top down mini golf game, and it works fine normally, but when i add a circle collider 2D it pretty much just breaks and the ball moves on its own, any ideas on whats causing that or how to fix it? The radius of the collider is larger than the ball

leaden ice
lethal crag
#

so why would it be working without the collider, what could cause the collider to move the ball on its own

maiden lake
#

is there any way i can connect a objet to a camera with script

maiden lake
#

i ran i to a isue with my networking when i nea to synch cams in base the cam has to be off nad if its of its not showing the IK

hollow kernel
lethal crag
# leaden ice define "working"?

it only moves when i want it to, when i hold right click, drag the mouse, and let go, then the ball finally moves. but with the collider attached, it just moves randomly when i play the scene

hollow kernel
charred forum
#

I've got a question about which is more efficient. Right now I have a prefab panel that will be instantiated multiple times, and the prefab has 3 children (hpSlider, hpTextValue and nameText). In this case, I need to be able to reference the children objects to change their values periodically. Is it more efficient to spawn in the full prefab and use Transform.Find() to get the children, or is it better to break the prefab into pieces and instantiate the panel, and then instantiate each child separately with the panel as the parent? As a worst case, I'll be instantiating up to 16 of these panels at a time at most.

hollow kernel
maiden lake
#

i tried

leaden ice
#

that script can reference its own internals and do what it needs to do

maiden lake
#

i was thinking about conceting the wapons to the cammera after the syncing of the cameras

#

so the ik will be shown in the prefab

hollow kernel
#

cant you move the camera as a whole

#

like using script

charred forum
hollow kernel
#

move it a bit to give a placebo effect

leaden ice
maiden lake
#

nah i nead a way that the camera stays disbale in orefab but the child in prefab unther the cam will be sean

charred forum
#

Ok, so on the script I would make public Slider and public Text variables and just drag in those parts of the prefab into the script on the parent prefab object?

maiden lake
#

i want to hand so be still the in the prefab even tho the camera is off so i can sync the cams and let other ppl see the IK

#

and it has to be under the cam otherwise the recoil,sway doesnt work

rigid island
lone relic
#

hey guys, im working on a game and am adding throwable grenades. I made this script but unity keeps giving me errors and dont know why, can anyone tell me what i am doing wrong? heres the script:
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Grenade : MonoBehaviour {

public float delay = 3f;

float countdown;
bool hasExploded = false;
// Start is called before the first frame update
void Start() {
    countdown = delay;
}


// Update is called once per frame
void Update() {
    countdown -= Time.deltaTime;
    if (countdown <= 0f && !hasExploded)
    {
        Explode();
        hasExploded = true;
    }
}

void Explode ()
{
    Debug.Log("imabatakam");
}

}
`

mellow sigil
#

Show the errors

lone relic
#

oh okay sorry

rigid island
lone relic
#

what

leaden ice
#

shar evideos as mp4 so discord can encode it please

maiden lake
#

@lone relic click on the erros and VS will show the line which is problematic

leaden ice
#

I can't download things on this laptop

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

lethal crag
#

bruh why did video send like that

rigid island
#

or mp4

lethal crag
rigid island
lethal crag
#

where should i do this then, im new to the unity disc
it was the circle collider, it just broke after i added it, the video shows it working just fine beforehand

woven dome
#

Hi there
does anyone know how to use FindSelectable properly in UI?
I'm trying to manage navigation of a GridLayoutGroup manually but the function doesnt returns only null...

_buttons = GetComponentsInChildren<Button> ().ToList ();
foreach ( Button button in _buttons ) {
    Quaternion rotation = button.transform.rotation;
    Navigation nav = new () {
        mode = Navigation.Mode.Explicit,
        wrapAround = true,
        selectOnDown = button.FindSelectable ( rotation * Vector3.down ),
        selectOnUp = button.FindSelectable ( rotation * Vector3.up ),
        selectOnRight = button.FindSelectable ( rotation * Vector3.right ),
        selectOnLeft = button.FindSelectable ( rotation * Vector3.left ),
    };
    button.navigation = nav;
}
upbeat dust
#

Heyy, working on DAY / NIGHT cycle
Im trying to lerp the color of camera's background color

Problem: the background changes instantly, instead of lerping, no matter the time i set

    Camera cam;
    public Color dayColor;
    public Color nightColor;

    // START
    void Start()
    {
        cam = GetComponent<Camera>();
    }

    // UPDATE
    void Update()
    {
        cam.backgroundColor = Color.Lerp(dayColor, nightColor, 10);
    }```
dim spindle
#

also

leaden ice
dim spindle
#

you need a value that updates

leaden ice
#

Color.Lerp(dayColor, nightColor, 10); is completely equivalent to just writing nightColor

dim spindle
#

it will always update instantly if you dont have a changing value

upbeat dust
leaden ice
#

it's just a math function

#

it doesn't spawn a coroutine or something

#

it just returns a value

upbeat dust
#

Oh, ok, thx, but is there a way to controll the time it takes?

leaden ice
#
float t = 0;
float duration = 10;
void Update() {
  t += Time.deltaTime;
  t %= duration;

  cam.backgroundColor = Color.Lerp(dayColor, nightColor, t / duration);
}``` something lioke this @upbeat dust
dim spindle
#

float time = 0;
void Update()
time += Time.deltaTime
Lerp(day, night, time / number_of_seconds)

#

exactly

#

mine is very pseudocode

upbeat dust
dim spindle
#

oh yeah %= is a good idea

dim spindle
upbeat dust
#

Perfect, tysm guys)

leaden ice
#

and have the start and end colors be the same

#

so it loops smoothly

upbeat dust
upbeat dust
simple ridge
#

Hi everyone, I am looking to store a value during the pre build step using the code below, this seems to work and I get a debug log in console telling me the correct Android.bundleVersionCode, however when trying to access this value again later through the player preferences, PlayerPrefs.HasString returns false for "Version". I'm thinking player preferences may not work during the pre-build phase, is there another way I can acomplish this?

#if UNITY_EDITOR
    using UnityEditor.Build;
    using UnityEditor.Build.Reporting;
    using UnityEngine;

public class BuildVersion : IPreprocessBuildWithReport
{
    public int callbackOrder => 0;
    
    public void OnPreprocessBuild(BuildReport report)
    {
        int version = UnityEditor.PlayerSettings.Android.bundleVersionCode;
        PlayerPrefs.SetString("Version", $"{version}");
        
        Debug.Log($" <color=#00AA99>§»</color> Build Version: {version}");
    }
}
#endif
leaden ice
simple ridge
#

Its editor only, so doesn't work in the build

leaden ice
#

well PlayerPrefs isn't going to set anything for the build either

#

PlayerPrefs is a local thing for your computer

#

it's not part of the build

simple ridge
#

Ah good point.. I forgot about that xD

leaden ice
#

it also is different in editor and in a build anyway

#

you'd have to write the data to a serialized asset

#

A ScriptableObject for example

#

or a file in StreamingAssets

simple ridge
#

Right, I'll look into that then. I've used SO's before so shouldn't be to hard to get that done. Thank you

#

Sorry, I was being a bit dumb xD

vestal crest
#

is there a way to merge materials in play time?

#

like i have the path of material. i change the material at runtime then when i stop playing i want to get that material and merge the actual asset

#

you can do smth like this with prefabs. prefabutility.mergeprefabinstance smth like this works fine

#

but i couldnt make it for material

#

is there a way to do it?

leaden ice
#

just make sure you're using .sharedMaterial instead of .material at runtime

#

.material makes a copy

vestal crest
#

thats not what i want actually

#

i want to keep .material

#

i want to get that instance material and find the actual material in assets (i have path of it) then merge it

#

something like this but this doesnt work

maiden lake
#

idk if im stupid but (its saying that playerCamera is unaccessble becous of security)

hexed pecan
#

Dont cross post please

leaden ice
# vestal crest

If goMaterials is an array of direct material references you can just modify them directly

#

there's no need to deal with AssetDatabase etc

#

and no need to make a new material

vestal crest
vestal crest
#

paths is path of the actual materials path

leaden ice
vestal crest
#

in assets folder

leaden ice
#

what does that mean

vestal crest
#

think of a simple cube get that renderer and its materials

leaden ice
#

according to your code it's just an array of materials directly

#

no cubes

#

no GameObjects

#

etc

#

and that's just fine

#

you can modify them directly

#

i.e. stop doing the new Material thing

vestal crest
#

i cant modify them because they are instance material when i stop playing changes dont save thats what im trying here

#

saving instance material

leaden ice
#

just... stop doing that

vestal crest
#

i know okay but what if i have to make them instance

#

thats all i ask

vestal crest
#

i know this but this is not what i want actually because if i do this way i will lose references

#

imagine of a prefab, if i do this i have to reference it in inspector

leaden ice
vestal crest
#

what i want like literally merge material

leaden ice
#

just modify the existing one

vestal crest
#

how can i do it?

#

if it is an instance material

leaden ice
#
  • get a reference to it
  • modify it