#archived-code-general

1 messages · Page 386 of 1

cursive moth
#

I was just recommended this interesting approach by gpt, idk if it's working(haven't tested yet) or bad practice, but I do like it because it gives you control over how each element is handled, I like that:

        public void LoadFromJson(string json)
        {
            using (JsonDocument document = JsonDocument.Parse(json))
            {
                JsonElement root = document.RootElement;

                if (root.TryGetProperty("General", out JsonElement generalElement))
                {
                    if (generalElement.TryGetProperty("FPS", out JsonElement fpsElement))
                    {
                        General.FPS = fpsElement.GetInt32(); // Calls the FPS setter and triggers event
                    }
                }
            }
        }
#

ofc I'd modularize it a bit but this is how it'd work ig

plucky inlet
#

But from what I just quickly read, I do not see any issues with your current class, that would prevent the json from overwriting the values. are you sure, you getting the right class structure and json attribute names etc?

cursive moth
#

but as Praetor said, it utilizes Unity's serialization technique, which means that it can't detect properties, again, if I am not mistaken ofc

#

and therefore, my current apprach is not valid

#

and I can't use fields because I need OnValueChanged events for live config reloading

plucky inlet
#

Do you really need to stick to get setters if you are loading it anyways? You then can just call an update on the whole config when loaded instead of the setters

cursive moth
#

it's a live system background that should use the least resources possible

chilly surge
#

What's the JSON storing? Is it storing some data that will be known at compile time and won't change at runtime? Is it your own data where you can store it in a different format, or is it some external data that you got from somewhere else and might change?

plucky inlet
cursive moth
plucky inlet
#

For me it sounds like you kind of overengineer the whole part because of an idea 😉

cursive moth
cursive moth
chilly surge
cursive moth
#

well, ig I'll use your advice and simplify this a lot

plucky inlet
cursive moth
#

and I need it to not be known at compile time, it's a config

chilly surge
#

Like the reason I'm asking if the data will ever change at runtime, is precisely that if it's known at compile time and won't change at runtime, you can just store it as a scriptable object or something else and skip the entire deserialization altogether.

plucky inlet
chilly surge
#

Unity already provides serialization mechanisms like scriptable object, if it fits then you don't need to go through the entire dance with JSON at all.

cursive moth
chilly surge
#

Why is it that the data must locate at that place?

cursive moth
cursive moth
chilly surge
#

Convenience for what?

cursive moth
#

for the users

chilly surge
#

So it's runtime config?

cursive moth
#

yes

plucky inlet
chilly surge
cursive moth
cursive moth
#

don't want to be wasting either of your times, I am having this discussion purely for fun and to possibly learn something new, I am already perfectly satisfied with the solution twentacle came up with

chilly surge
plucky inlet
chilly surge
#

Configs are usually structured data, you shouldn't access your config like it's unstructured data.

cursive moth
plucky inlet
chilly surge
#

JsonDocument/JsonElement/etc are APIs to access unstructured data. It's effectively the same as writing reflection code.

plucky inlet
#

So, just simplify it, done 😄

cursive moth
#

I came up w that idea purely because I needed to assign json values directly to properties, ik it's not the best approach because it requires a lot of additional code etc.

cursive moth
chilly surge
#

You should have a class that matches the structure of your config and deserialize into that directly.

thin aurora
#

You have a general object with key-value pairs. So you have a Dictionary

#

So you can just deserialize as a Dictionary<string, string>

#

As pointed out JsonDocument/JObject is for unstructured/dynamic data and you should only use this if the type is either unknown or can be multiple things. Your data is very much structured

cursive moth
#

I see, that makes sense, I already wrote the new implementation(p much what you suggested) and will test it now, thanks

thin aurora
#

Should correct myself, the value in your pair can be multiple values. I suggest you either stick to string and convert as needed, or use JValue for the value (I don't remember what the STJ equivalent is)

digital summit
#

Thanks man!

#

Thank you too man!

warm cosmos
#

is it possible to add my own layers to physics for physics2d?

#

I would like certain gameobjects to have collisions for their own layer, so that boxcast/circlecasts can check for these specifically with a layer mask without checking everything else

cursive moth
#

doesn't seem like a coding question, but anyways, just add a layer?

spring basin
warm cosmos
#

yeah

spring basin
#

and set the collisions in the matrix in project settings

#

but if you want to check the collision for different layers on different objects.. you can provide layermask in the Spherecast

warm cosmos
#

thanks guys 👍

torpid sand
#

Anyone have a line extrude script they could share, utilizing unity's splines?

ivory smelt
#

Last windows update fumbled my .Net install and I had to update to the last one, now my vscode ESLint aint working correctly with unity projects, does anyone know how to fix it?

#

MonoBehaviour functions shouldnt appear as shaded since they are not unused methods regardless of not being called from code, it used to be displayed the right way

latent latch
latent latch
ivory smelt
latent latch
#

you usually download .net dev and sdk manually then

ivory smelt
#

yeah, i just updated to 9.0

#

thats what caused the issue

#

but it forced me to update otherwise it directly would not work at all

#

:(

calm mountain
#
public class VersionController : NetworkBehaviour
{
    private static VersionController _instance;

    private void Awake()
    {
        // Ensure only one instance of VersionController exists
        if (_instance == null)
        {
            _instance = this;
        }
        else if (_instance != this)
        {
            Destroy(gameObject);
            return;
        }
    }

    public static bool ValidVersionNumber()
    {
        Debug.Log(_instance);
        return _instance.ValidVersionNumberInternal();
    }

Whenever I call ValidVersionNumber(), I am getting null for _instance, and I'm not sure why

ivory smelt
#

is NetworkBehaviour a MonoBehaviour?

somber nacelle
calm mountain
somber nacelle
#

yeah so then Awake never runs, meaning _instance is always null

#

is there a specific reason this is a NetworkBehaviour and not just like a plain class?

calm mountain
#

Yeah, didn't catch that. Thanks!

#

Yeah I'm using Fish networking package

somber nacelle
#

that doesn't explain why this object is a networkbehaviour. what reason do you have for making this specific object inherit from networkbehaviour

calm mountain
#

I'm following a template from a guide, that's basically what I can tell you

#

Just trying to make it work on a slightly different application

somber nacelle
#

well from the sound of it, you have literally no reason for this to inherit from NetworkBehaviour

calm mountain
#

👍

golden chasm
#

I am attempting to install the Apple Unity Plugins but when i attempt to build using python3 build.py as stated in the documentation it just keeps saying The following build commands failed: Run custom shell script 'Run Script' I have xcode installed and python3 (3.13).

digital bobcat
#

Chat can someone help me

trim schooner
tawny elkBOT
flint plume
#
if (Input.GetKey(KeyCode.A))
        {
            RotateX = 1;
        }
        else if (Input.GetKey(KeyCode.D))
        {
            RotateX = -1;
        }
        else
        {
            RotateX = 0;
        }

        if (Input.GetKey(KeyCode.W))
        {
            RotateZ = -1;
        }
        else if (Input.GetKey(KeyCode.S))
        {
            RotateZ = 1;
        }
        else RotateZ = 0;

        Vector3 UA = transform.localEulerAngles;
        Vector3 rotation = new Vector3(UA.x + RotateX, UA.y, UA.y + RotateZ);

        // Smoothly interpolate the current rotation to the target rotation using Slerp
        transform.localRotation = Quaternion.Slerp(transform.localRotation, Quaternion.Euler(rotation), 0.0005f * Time.deltaTime
        );
#

tried using old code too 💀

rapid glen
#

o damn yeah maybe you should hastebin stuff like that in future 😛

#

!code

tawny elkBOT
flint plume
#

i can send just the rotation logic if you want

#

the rest is just context for how im getting the initial rotation inputs

#
Vector3 UA = transform.localEulerAngles;
        Vector3 rotation = new Vector3(UA.x + RotateX, UA.y, UA.y + RotateZ);

        // Smoothly interpolate the current rotation to the target rotation using Slerp
        transform.localRotation = Quaternion.Slerp(transform.localRotation, Quaternion.Euler(rotation), 0.0005f * Time.deltaTime);
rapid glen
#

all good yeah for now only need these three lines

flint plume
#

im trying to make a wingsuit btw

#

this is the inspiration

#

just cause 3 also has a really good wingsuit

rapid glen
# flint plume just cause 3 also has a really good wingsuit
Vector3 currentRotation = transform.localRotation.eulerAngles;

// Incrementally apply changes to the current rotation
currentRotation.x += RotateX * Time.deltaTime;
currentRotation.z += RotateZ * Time.deltaTime;

// Apply the updated rotation
transform.localRotation = Quaternion.Euler(currentRotation);
``` you can do this in Update()
#

or a method that is called in update

#

You can multiply if it's not fast enough

currentRotation.x += RotateX * Time.deltaTime * 10f;
currentRotation.z += RotateZ * Time.deltaTime * 10f;

raven bobcat
#

Hello everyone, I have a question here:
When my character moves sideways, it keeps shaking.
I am not sure if it is caused by my Physic-based input system or Cinemachine.
I had tried changing the camera Update Method, but notthing seem to work. What could be the issus?

#

The movement code look like this:

    private void FixedUpdate()
    {
        grounded = Physics.Raycast(transform.position, Vector3.down, objectHeight * 0.5f + 0.2f, whatIsGround);

        Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
        float MaxSpeed = isSprinting ? sprintSpeed : moveSpeed;

        if (grounded && flatVel.magnitude < MaxSpeed)
        {
            Vector3 moveDir = new Vector3(moveDirection.normalized.x, 0f, moveDirection.normalized.z);
            rb.AddForce(moveDir.normalized * MaxSpeed * 10, ForceMode.Force);
        }
        else if (!grounded && flatVel.magnitude < MaxSpeed)
        {
            Vector3 moveDir = new Vector3(moveDirection.normalized.x, 0f, moveDirection.normalized.z);
            rb.AddForce(moveDir.normalized * MaxSpeed * 20, ForceMode.Force);
        }
        if (moveDirection.normalized == Vector3.zero)
        {
            isSprinting = false;
        }
    }
leaden ice
#

or if you have interpolation, something in your code is breaking the interpolation

#

a common source of this is rotating the object via the Transform

#

You'd have to show more of your code to tell for sure. For example - your code for rotating the player along its movement direction.

#

But first you should make sure interpolation is enabled on the Rigidbody

raven bobcat
leaden ice
#

any direct manipulation of the Transform will break interpolation

raven bobcat
# leaden ice You'd have to show more of your code to tell for sure. For example - your code f...
    private void LateUpdate()
    {
        Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
        orientation.forward = viewDir.normalized;

        if (Input.GetKeyDown(KeyCode.Mouse1))
        {
            currentStyle = CameraStyle.Aim;
            combatCam.SetActive(false);

        }
        if (Input.GetKeyUp(KeyCode.Mouse1))
        {
            currentStyle = CameraStyle.Basic;
            combatCam.SetActive(true);
        }

        //rotate player
        if (currentStyle == CameraStyle.Basic)
        {

            float horizontalInput = Input.GetAxis("Horizontal");
            float verticalInput = Input.GetAxis("Vertical");
            Vector3 inputDir = orientation.forward * verticalInput + orientation.right * horizontalInput;

            if (inputDir != Vector3.zero)
            {
                playerObj.forward = Vector3.Slerp(playerObj.forward, inputDir.normalized, Time.deltaTime * rotationSpeed);
            }

        }
        else if (currentStyle == CameraStyle.Aim)
        {
            Vector3 dirToCombatLookAt = combatLookAt.position - new Vector3(transform.position.x, combatLookAt.position.y, transform.position.z);
            orientation.forward = dirToCombatLookAt.normalized;

            playerObj.forward = dirToCombatLookAt.normalized;

        }
    }
leaden ice
#

!code

tawny elkBOT
leaden ice
#

But yeah you're directly modifying the Transform here

#

in a couple places

#

SO that's why your interpolation is breaking

#

you must rotate the object via the Rigidbody only.

raven bobcat
#

Ah...Okay thx

#

I think this could be an easy fix

leaden ice
#
playerObj.forward = dirToCombatLookAt.normalized;```
Can probably just change to:
```cs
rb.rotation = Quaternion.LookRotation(dirToCombatLookAt);```
raven bobcat
#

How abot the Basic camera?

leaden ice
#
Quaternion rotation = Quaternion.LookRotation(Vector3.Slerp(playerObj.forward, inputDir.normalized, Time.deltaTime * rotationSpeed));
rb.rotation = rotation;```
#

similar

#

this might play a little weirdly though. given the second layer of interpolation here in LateUpdate. Some of this might need to move to FixedUpdate and use rb.MoveRotation.

#

Try this first and see if it helps

#

this is really not a proper Slerp in any case.

raven bobcat
#

The code does not know fix the issus. I think you are right about how modifying the Transform directly could cause the issus.
I want to look into it more, but I have to go to work rn, do u mine if I pin you later?

raven bobcat
leaden ice
#

but would be easier to manage that way probably

#

It's weird to rotate the player inside the camera script, certainly

raven bobcat
#

OK, thanks for your advice👍

north shore
#

does anyone know a good method to shoot a raycast from under a collider by getting the position?

#

or concepts

leaden ice
north shore
leaden ice
north shore
#

i should say the ray position is supposed to be at the bottom on the second cuboid

spare dome
#

place the raycast on the center of the object, and change the length of the raycast based off of half the size of the Y scale (or bounds/extents) of the object plus an offset for the ground hit (also make the raycast direction point down in the local or global vectors)

leaden ice
#

using bounds could certainly work if you only care about the bounding box

strange tendon
#

How exactly does root motion get applied? I'm trying to just zero out an object's z-position like this in either Update or LateUpdate:

transform.position = new Vector3(transform.position.x, transform.position.y, 0);

...but for some reason that's reducing the x speed from the root motion as well, and I'm not sure why.

strange tendon
#

Fixed by using the OnAnimatorMove built-in function, which gets called whenever root motion is processed:

    void OnAnimatorMove()
    {
        Animator animator = GetComponent<Animator>();
        if (animator)
        {
            Vector3 newPosition = transform.position + animator.deltaPosition;
            newPosition.z = 0;
            transform.position = newPosition;
        }
    }

Still not positive why setting the position in Update instead wouldn't work.

frank hearth
#

I have a number generator but i think that my text object is broken or something. Whenever i try to generate the random numbers it only generates on the first Text Slot and not the second one. I tried switching their places in the script but the second text slot is always 1. What do i do?

#
using UnityEngine.UI;
using System.Collections.Generic;

public class RandomTextAssigner : MonoBehaviour
{
    public Text firstText; // Reference to the first Text component
    public Text secondText; // Reference to the second Text component

    public void AssignRandomNumbers(HashSet<int> usedNumbers)
    {
        // Generate a unique random number for the first text (0-9)
        int firstNumber;
        do
        {
            firstNumber = Random.Range(0, 9);
        } while (usedNumbers.Contains(firstNumber));
        usedNumbers.Add(firstNumber); // Add to the used numbers

        // Generate a unique random number for the second text (1-9)
        int secondNumber;
        do
        {
            secondNumber = Random.Range(1, 9);
        } while (usedNumbers.Contains(secondNumber));
        usedNumbers.Add(secondNumber); // Add to the used numbers

        // Assign the random numbers to the text components
        firstText.text = firstNumber.ToString();
        secondText.text = secondNumber.ToString();
    }
}
#

I also use a code that randomly places the notes at specific positions

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class RandomSpawn : MonoBehaviour
{
    public GameObject originalObject; // The prefab to instantiate
    public List<Transform> specifiedPositions; // List of specified positions to spawn the prefab
    private HashSet<int> usedNumbers = new HashSet<int>(); // Set to keep track of used numbers

    void Start()
    {
        // Check if the list is empty
        if (specifiedPositions.Count == 0)
        {
            Debug.LogWarning("No specified positions available for spawning.");
            return;
        }

        // Iterate through the specified positions and instantiate the prefab at each location
        foreach (Transform position in specifiedPositions)
        {
            // Spawn the prefab at the position's location and rotation
            GameObject instance = Instantiate(originalObject, position.position, position.rotation);

            // Optionally, add the RandomTextAssigner component to the instantiated prefab
            RandomTextAssigner textAssigner = instance.AddComponent<RandomTextAssigner>();

            // Find the Text components in the instantiated prefab
            textAssigner.firstText = instance.GetComponentInChildren<Text>();
            textAssigner.secondText = instance.GetComponentInChildren<Text>();

            // Assign random numbers ensuring uniqueness
            textAssigner.AssignRandomNumbers(usedNumbers);
        }
    }
}

#

Any help will be apreciated ❤️

latent latch
#

GetComponentInChildren will always return the first component instance it finds

#

check out the docs for other variations

echo smelt
#

Hi all. I'm currently updating my ios project to work with the latest version of Unity Cloud Build. Right now this old script I was using doesn't pull up the proper path for the build on ios to upload online. path="$WORKSPACE/.build/last/$TARGET_NAME/build.ipa" isn't found. Does anyone know where I can find the current location of the ios build?

Please @ me or reply in a thread if you have an answer.

 
#!/bin/bash
 
echo "Uploading IPA to Appstore Connect..."
 
#Path is "/BUILD_PATH/<ORG_ID>.<PROJECT_ID>.<BUILD_TARGET_ID>/.build/last/<BUILD_TARGET_ID>/build.ipa"
path="$WORKSPACE/.build/last/$TARGET_NAME/build.ipa"
# TODO: This shouldn't be hardcoded 
 
 echo "Files in workspace include:" 
 ls "$WORKSPACE/.build/last/$TARGET_NAME/"
 
if xcrun altool --upload-app --type ios -f $path -u $ITUNES_USERNAME -p $ITUNES_PASSWORD ; then
    echo "Upload IPA to Appstore Connect finished with success"
else
    echo "Upload IPA to Appstore Connect failed"
fi
grand skiff
# frank hearth I have a number generator but i think that my text object is broken or something...

Few things you can check:

Verify the Hashset like :

Debug.Log($"First number: {firstNumber}, Second number: {secondNumber}");
Debug.Log($"Used numbers: {string.Join(", ", usedNumbers)}");

Also try this:

public void AssignRandomNumbers()
{
(0-9)
int firstNumber = Random.Range(0, 10); // Range 0 to 9 inclusive

int secondNumber;
do
{
    secondNumber = Random.Range(1, 10); 
} while (secondNumber == firstNumber);

firstText.text = firstNumber.ToString();
secondText.text = secondNumber.ToString();

}

raven bobcat
# leaden ice SO that's why your interpolation is breaking

After some debugging, I found that the main problem is not the rotation, but the movement code
if (grounded && flatVel.magnitude < MaxSpeed) { Vector3 moveDir = new Vector3(moveDirection.normalized.x, 0f, moveDirection.normalized.z); rb.AddForce(moveDir.normalized * MaxSpeed * 10); } else if (!grounded && flatVel.magnitude < MaxSpeed) { Vector3 moveDir = new Vector3(moveDirection.normalized.x, 0f, moveDirection.normalized.z); rb.AddForce(moveDir.normalized * MaxSpeed * 20); //Debug.Log(moveDirection.normalized * MaxSpeed * 10); }
I try to limit the Max speed by adding this line**&& flatVel.magnitude < MaxSpeed** into my if stament which create a inconsistent velocity.

#

Is there another way to limit the max speed?

#

Also, I can't set the velocity directly, because it will override my dash function. ( When the player press the dash key, it will apply a force to quickly move the character sideways. Setting the max speed directly will break this function.)

public bool SprintAction() { if (moveDirection != Vector3.zero) { rb.AddForce(moveDirection.normalized * horizontalThrust, ForceMode.Impulse); isSprinting = true; return true; } return false; }

leaden ice
#

Although your code could certainly be jittering by going above and below your max speed rapidly

raven bobcat
#

I removed the speed limit and the character no longer shaking anymore

#

So I assume this is what causing the issue

leaden ice
raven bobcat
night wolf
#

Hello, I'm using Unity 6 and Digital Asset Manager in my application. I have a prefab uploaded to the Unity's Asset Manager. I can see this prefab in the Asset Manager window of my Unity 6 application. I want to use the Unity's Services Web API to manage this asset. First I use this command to get the idToken: https://player-auth.services.api.unity.com/v1/authentication/anonymous. I provide the projectid in the header of this command and it gives me the idToken, sessionid etc. Then I use this command to get download URLs of the asset: https://services.api.unity.com/assets/v1/projects/{projectId}/assets/{assetId}/versions/{assetVersion}/download-urls. I provide the projectID, assetId and assetVersion in this command and also provide header: Authentification as Bearer {idToken}. Problem is that I receive "unauthorized" as response. What am I doing wrong? I'm following all that's mentioned here: https://services.docs.unity.com/assets-manager/v1/#tag/Asset-management/operation/assets_v1_Assets_GetAssetDownloadUrlsAsyncV1. I'm sharing my code here in the attached file

elder flax
#

not entirely sure where to put this but i find it kind of infuriating that when i copy paste an object, it copies and pastes the WORLD position. this means when i copy a child of another object and put it to another thing (same object), its in the original spot it was in. would be SO much better for me right now if it copied the local position so i didnt haev to manually reposition it every time

placid summit
#

I use singleton monobehaviours sometimes, but if you have one that starts off inactive you hit the issue of needing the static Instance variable to be init before it is accessed 9usually done in Awake)! Is there a snippet/pattern that covers this?

plucky inlet
plucky inlet
placid summit
elder flax
plucky inlet
#

I just try to get your point. If you need an instance of that thing, why would it be inactive at all? Just dont turn it off, if you need it. And if its running things on its own you dont want, because you just used awake and start and what not, you might need to refactor your singleton mono to actually behave controlled and not on its own

placid summit
#

a Ui panel can be a singleton and making sure it is visible at start is not ideal. But then the singleton pattern is not that ideal!

lean sail
plucky inlet
placid summit
placid summit
plucky inlet
lean sail
plucky inlet
#

If you need to select objects of some "kind", which sounds like you do by abusing a lot of singletons for your needs, you rather should create a generic ui class of some sort with an enum or wahtever and have a singleton active controlling those things. If you wanna go full generic, there still has to be some structure for you to work with

placid summit
#

I have seen people use the scene search method but yes I think it is not great so will use an alternative

plucky inlet
lean sail
placid summit
#

But I avoid scene searches at all cost so agree

plucky inlet
#

Well, you answered your own point then. Do not do it and refactor your setup to work as singletons and dynamic UI should be set up.

#

you can always describe, what you are trying to do with all those singletons and why, so we can get some suggestions in, that help you

placid summit
#

you know I realize i just over-use singletons when I could have 1 singleton with references to components or directly reference components wherever needed in this case. I definitely go to the singleton pattern too often!

plucky inlet
thin aurora
#

If you want to really make this work, I suggest you make it an actual service provider where you register managers and then grab them from. It is incredibly useful to have DI done that way

#

Maybe even configure managers based on lifecycle. For example, singleton managers or managers that persist until the scene unloads that it exists in

worn star
#

hi

#

to get the inital velocity of projectile should i devide FORCE(forcemode.impluse) by its rb.mass?

gentle willow
#

Hi I hope I dont interrupt anyone but does someone here know a good tutorial where I can learn how to create a card system so the player can choose between 3 cards?

dusky lake
dusky lake
gentle willow
#

So the player buys a card pull. After that he can choose between 3 different upgrades that are displayed as "cards"

#

My game is going to be a clicker roguelike if that helps

dusky lake
gentle willow
#

thats to bad

worn star
#

basically I want to calculate its trajectory , but i dont know how to relate force i am applying with initial velocity cuz idk what unity add force means like in terms of physics

#

is F = m (deltaV)

dusky lake
worn star
frank hearth
grand skiff
frank hearth
nova leaf
#

i have a camera that i want to follow the player (rigidbody) and rotate, but also rotate the player... if i rotate both the player and camera in the same update (no matter if late, normal or fixed) i get desync and jittery model rotation, and if i split it it and rotate the model in fixed it does too. help.

plucky inlet
nova leaf
plucky inlet
nova leaf
# plucky inlet Ah, k, you never mentioned and usually thats what most of the people run into, w...

i did mention as i said.
i didnt share because doesnt matter what i do it doesnt work, and rn i dont know what to put where

        float mouseX = Input.GetAxisRaw("Mouse X") * sensX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * sensY;

        yRotation += mouseX;
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        Quaternion camTargetRotation = Quaternion.Euler(xRotation, yRotation, 0);
        camHolder.position = head.position;
        camHolder.rotation = Quaternion.Slerp(camHolder.rotation, camTargetRotation, rotationSpeed * Time.deltaTime);
        ///idk where to put that
        model.rotation = Quaternion.Euler(0, yRotation, 0);

model is a rigidbody

spare dome
#

you should put anything rigidbody related into FixedUpdate so it resides on the physics step and the rest in LateUpdate
Also it sounds like an interpolation breaking issue

#

you could use MoveRotation to make it respect the interpolation of the rigidbody as well

nova leaf
glacial mountain
#

Anyone have an idea how to make this work? IE: Serialized Vars aren't showing.


using Object;
using UnityEngine;
using UnityEngine.UI;

namespace InventorySystem
{
    public class InventoryItemButton : Button
    {
        [SerializeField] private Item attachedItem;
        [SerializeField] private new Texture image;
        
        public Item GetAttachedItem() => attachedItem;
        public void SetAttachedItem(Item newAttachedItem) => this.attachedItem = newAttachedItem;
    }
}

knotty sun
#

make the class serializable

glacial mountain
#

oh

#

Thanks Steve

#

Let me try that

#

Just this yea. ```c#

namespace InventorySystem
{
[Serializable]
public class InventoryItemButton : Button

knotty sun
#

System.Serializable

#

probably need to do the same for Item as well

spare dome
#

you could try that to see if it works

glacial mountain
#

nada

nova leaf
spare dome
#

you just rotate that instead of the player's transform, works for me🤷‍♂️

nova leaf
#

that doesnt make any sense

#

maybe if the players model is a bean then yea

spare dome
#

well the model rotates with it

#

and it has glasses as every bean should have

nova leaf
#

🤦🏻‍♂️

spare dome
#

well I did it to reduce jitter of the camera and jitter of the rigidbody on my character, which is does effectively I believe

knotty sun
#
using UnityEditor;

[CustomEditor(typeof(InventoryItemButton))]
public class InventoryItemEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
    }
}
nova leaf
# spare dome well I did it to reduce jitter of the camera and jitter of the rigidbody on my c...

nevermind rotating it in update works fine if i use the model as a child of the rigidbody , the code line for placing the cam at the head and rotating the player (parent of the head) was in wrong order, i placed the head first and then rotated the model which caused the jittering. problem is just now the model is not synced in multiplayer anymore as a child of the player with an independant rotation, and i have to give it it's own network transform? idk

spare dome
#

ah I never would have guessed that as I change the transform of the camera in a separate script completely, also I know nothing on how multiplayer works, so I cannot really help that far

glacial mountain
#

@knotty sun GG m8

#

Appreciate

knotty sun
# glacial mountain

you only need the Editor script because Button has a custom inspector which you need to override

glacial mountain
#

Thank you for letting me know that

unborn elm
#

Hi. I have a timer that uses a float value and then I have a helper class to recalculate that as year, season and days. It all works well but every time I do the calculations I construct a new
struct. Are there any kind of problems with this memory and calculation-wise. In my heads its not diffrent than doing a new vector but still want to check;


 public static TimeStruct TimeToTimeStruct(float time)
    {
        int intTime = Mathf.FloorToInt(time);
        int newYear = TimeToTimeStructElement(iTime,TimeElementEnum.year,out iTime);
        int newSeason = TimeToTimeStructElement(iTime, TimeElementEnum.season, out iTime);
        int newDay = iTime;

        TimeStruct timeStruct = new TimeStruct { year = newYear, day = newDay, season = newSeason};
        return timeStruct;
    }
public struct TimeStruct
{
    public int day;
    public int season;
    public int year;
}
thick terrace
unborn elm
#

Is it generally better compared to a reffrence type?

thick terrace
rigid island
#

always keep my value types in structs

#

micro-optimization but why not

#

as soon as you add a ref then you kinda don't need a struct at that point since it will still go on heap

#

btw you can just make the TimeToTImeStruct a method of the TimeStruct class

late lion
maiden fractal
#

That's how I thought too

rigid island
#

is it? oh I think i misunderstood it then, I was under the impression that having a ref type would making part of heap

leaden ice
leaden ice
#

Same with in and out

rigid island
#

ohh so

    public struct ABC{
        public MyClass myClass; 
    }
    public class MyClass{
        public int numberThing;
    }```
ABC still goes on the stack ?
maiden fractal
leaden ice
#

it depends on the context in whihc the variable of type ABC is declared

maiden fractal
#

true

rigid island
#

ahhh okay I think it makes a bit more sense now

leaden ice
# rigid island ohh so ```cs public struct ABC{ public MyClass myClass; } ...

For example:

    public struct ABC{
      int y;
    }
    public class MyClass{
        public ABC abc; // <-- this ABC is a member of the class object which will be in the heap, so it will be in the heap
    }

    void Example() {
       ABC test = new(); // <-- this ABC lives on the stack
    }

    void Ex2(ABC input) { // <-- this ABC lives on the stack

    }```
rigid island
latent latch
#

ref all struct parameters

leaden ice
#

or at least in them

late lion
#

Depends on the size of the struct. A ref is always 8 bytes in 64-bit applications. A single int is just 4 bytes.

#

That said, I don't think there's any performance difference when the size is small. I think after about 44 bytes, Mono has to use a more expensive method of copying structs, so ref or in becomes significantly faster.

maiden fractal
#

From the unity structs, Matrix4x4 at least would be over 44

late lion
#

Yeah, it's 64 bytes. That's the only one I know from Unity that goes over.

#

This will probably not apply anymore once CoreCLR is merged. And might not apply for IL2CPP in builds, not sure.

chilly surge
# latent latch ref all struct parameters

When you pass value types by ref you avoid the cost of copying the struct, but you add an extra deref overhead every time you access that value. For smaller structs the cost of dereffing might outweigh the benefit of avoiding a copy.

chilly surge
# leaden ice or at least `in` them

in also has the dereffing cost similar to ref talked about above, on top of that in makes the guarantee that when you call Fn(in x), you are guaranteed that x won't be mutated even if Fn's code does something like x.Mutate(). And that poses a problem to the compiler that in some cases there's not really a way to guarantee it other than making a copy of x, which completely nullifies the benefit of passing by in.
To avoid defensive copy, the best practice is to make the x struct readonly, so that compiler knows it can't be mutated. That's easy to do if you own the struct, but if the struct comes from third party code, then you might be in a situation where you are not sure if using in is even buying you anything performance-wise.

short osprey
#

heya, i'm trying to get a grayscale effect to work.

This game is a platformer where by pressign shift the screen freezes and lets the player choose to rotate the room by 90, 180 or 270 degrees. this is all working perfectly. However, im trying to make it so that post processing causes a grayscale effect (by seting saturation to -100) whenevr youre in the menu that lets you pick a direction. Code below,
the debug asserts seen above all succeed, yet no visual effect is happening.

#

[RequireComponent(typeof(PostProcessVolume))]
public class Grayscaleshifter : MonoBehaviour
{
    private PostProcessVolume postProcessor;

    [SerializeField] private float secondsToGray;
    [SerializeField] private float secondsToColorWhenCanceled;

    // Start is called before the first frame update
    void Start()
    {
        postProcessor = GetComponent<PostProcessVolume>();

        GameStateManager.Instance.CurrentStateChanged += HandleStateChange;
    }

    void OnDestroy()
    {
        GameStateManager.Instance.CurrentStateChanged -= HandleStateChange;
    }

    void HandleStateChange(GameStateChangedContext context)
    {
        if(context.NewState == GameState.GravityMenu)
        {
            StartCoroutine(FadeToGrayscale());
        }
        else if(context.NewState == GameState.Rotating)
        {
            StartCoroutine(FadeToColored(RoomManager.ROOM_ROTATION_TIME_SECONDS));
        }
        else if(context.NewState == GameState.Playing && context.PreviousState == GameState.GravityMenu)
        {
            StartCoroutine(FadeToColored(secondsToColorWhenCanceled));
        }
    }

    IEnumerator FadeToGrayscale()
    {
        float timePassed = 0;

        while (timePassed < secondsToGray)
        {
            postProcessor.weight = Mathf.Lerp(0, 1, timePassed / secondsToGray);
            timePassed += Time.unscaledDeltaTime;
            yield return null;
        }
        Debug.Log("Gray");
        postProcessor.weight = 1;
        Debug.Assert(postProcessor.weight == 1);
    }

    IEnumerator FadeToColored(float duration)
    {
        float timePassed = 0;

        while (timePassed < secondsToGray)
        {
            postProcessor.weight = Mathf.Lerp(1, 0, timePassed / duration);
            timePassed += Time.unscaledDeltaTime;
            yield return null;
        }
        Debug.Log("Colored");
        postProcessor.weight = 0;
        Debug.Assert(postProcessor.weight == 0);
    }
}
chilly surge
pliant frigate
#

Hi in my game i can't look up, does someone knows how to fix it?

knotty sun
somber nacelle
tawny elkBOT
potent sundial
#

Hello, im going crazy over configuring navmesh at runtime, Ive tried following 3 different tutorials, and following the advice on some forums but i have not been able to set it up correctly. Ive reinstalled the package, deleted the library folder and reloaded it, restart the PC and Unity, and nothing, i have not been able to get around this.

if anyone needs some more info lmk please, i have no clue what else to try here

somber nacelle
#

first, get your IDE configured using the guide linked directly above your message.
after you do that and see errors underlined in your code, provide information like your unity editor version and the version of the ai navigation package you are using

potent sundial
#

the bulb did it for me and then it didnt show any errors, even if i was typing the exact same thing as what the tip did

#

but console still had errors

somber nacelle
#

are you using asmdefs in your project? and if so, did you fail to reference the ai navigation package in your asmdef?

potent sundial
somber nacelle
#

did you look in your project files to see if you have any in that path?

potent sundial
#

ill check, havent yet

#

Ok i see the ones related to the AI navigation package

somber nacelle
#

obviously the package will have them. that isn't important though, check if you have asmdef files

potent sundial
#

oh ok yeah here, i do have some, i guess since i started from one of the unity templates that had them by default i didnt realize

somber nacelle
#

so find the asmdef file that your code is a part of and add the reference to the ai navigation package there

rustic ember
#

Hi! I have a set of points (forming a circle) that I want to project onto two triangles in a mesh generator. I essentially need a hole in the two triangles that is circular. In other words, I need to find the y-position of the triangle at the XZ-coordinates of the points. I know the position of each vertex that forms the two triangles. I also know the XZ-coordinates of each point. Additionally, I know which triangle the point is over. Can someone help me find a solution? Or maybe point me in the right direction? Thanks in advance 😊

(Picture is from Blender to illustrate what I mean)

#

(Here's a picture of what I want to achieve in the end)

#

But for now, I just need a way to get the y-position of one point. I can work the rest out myself, I believe

maiden fractal
steady moat
maiden fractal
steady moat
maiden fractal
#

Maybe I'm just stupid but I don't get it

rustic ember
maiden fractal
#

It has constructor with 3 points as input

steady moat
#

Also, Plane.Raycast is the same.

rustic ember
maiden fractal
#

new Plane(pointA, pointB, pointC).Raycast(new Ray(xzPosition, Vector3.up), out float yHeight) should output the height as yHeight

maiden fractal
#

xzPosition must just have y position of 0, otherwise it will be added up to the result

steady moat
maiden fractal
#

I also thought of maybe using barycentric coordinates/interpolation which might allow to easier figure out whether the point is within the triangle or not but I have never used them so not really sure how easy that would be

#

It might be little bit faster too but using Plane isn't bad either. The slowest part of the whole raycast process is the constructor of the Plane which normalizes the normal vector which requires one SQRT

rustic ember
#

I want to save the Plane as a variable to use multiple times, right?

maiden fractal
#

Didn't even realize that. That makes the process a lot faster

#

As I said, constructing the Plane is the slowest part

steady moat
#

You could just use the plane equation ?

Ax + By + Cz + D = 0
Where (A,B,C) = the normal and D = the distance from the normal.
You can just find the value of y

rustic ember
#

It is part of a World Generator I'm writing, so it doesn't have to be fast, but it's still nice to improve performance wherever I can ☺️

rustic ember
maiden fractal
#

The Raycast itself is just two dot products and a division so shouldn't be too bad for performance. Sim is likely correct in that there is faster way in this specific case though

#

my math ain't mathing today so I'll leave that to sim

rustic ember
leaden ice
#

Certianly would reccomend Plane.Raycast until and unless you have a demonstrated performance constraint with that method. It's very fast.

leaden ice
#

There's a Java implementation on that wikipedia page that could easily be adapted to C#

maiden fractal
#

That alone seems to be as slow if not slower than the raycast. I'm still wondering whether you could combine these two operations with barycentric interpolation/coordinates somehow but I have actually no idea how that works. This method is very fast anyways

maiden fractal
maiden fractal
# leaden ice Or just this!? https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_inters...

I think the performance difference in this case would be very little and I actually would be surprised if the Raycast method wouldn't be faster. Because in this special case the intersection test can be simplified to 2D triangle intersection which seems to be very fast, there isn't much benefit for doing the 3D intersection test. @rustic ember In this case you would actually want to do the intersection test first to not have to raycast at all if the point is outside the triangle which would also save some execution time

leaden ice
#

but if it is a world axis plane, then I agree

maiden fractal
#

The Möller–Trumbore algorithm also seems to have benefit of "without needing precomputation of the plane equation of the plane containing the triangle" but in this case actually calculating the plane equation is fine because it can be used for multiple points

maiden fractal
fallow quartz
#

when I should not be using static methods?

maiden fractal
fallow quartz
maiden fractal
fallow quartz
maiden fractal
#

I'm not familiar with static events, sorry

somber nacelle
rigid island
#

or like I use static events to register a specific object to Manager

#

eg

public class Damageable : MonoBehaviour
{
    public static event Action<Damageable> OnRegister;
    public static event Action<Damageable> OnUnregister;

private void OnEnable()
{
OnRegister?.Invoke(this);
}

public class AudioManager : MonoBehaviour
{
    private void Start()
    {
        Damageable.OnRegister += Destructible_OnRegister;
        Damageable.OnUnregister += Destructible_OnUnregister;
    }```
```cs
 private void Destructible_OnRegister(Damageable obj)
 {
     if (map.ContainsKey(obj)) return;
     map.Add(obj, DestructibleAudioSource);
     obj.OnDestroyed.AddListener(OnDestruCtibleDestroyed);
 }```
storm wolf
#

Events saved my life

tame anchor
#

I have a 3rd-party dll that has embedded resources. While I can use this dll in the unity editor, the resources get stripped out when I do a webgl build and I get an error "Could not find any resources appropriate for the specified culture or the neutral culture". It asks me to make sure they were embedded in the DLL, which I have confirmed with dotpeek, but they are gone after a build 😦

thick terrace
tame anchor
#

I hear you, but it's a 3rd-party dll that I have a dependency on...

thick terrace
#

you would probably have to extract the resources into your project as assets and modify the DLL

tame anchor
#

Is that doable with external DLLs? It is actually a dependency of another external dll...

thick terrace
#

what do you mean an external DLL? i guess you have to include it in the project somehow?

tame anchor
#

I put the DLL/assembly in my project and Unity finds it. In the inspector, it asks what targets to include it for, and I select the WebGL target. Most of what is in it runs, but I get an error whenever it tries to access the embedded resources..

#

It's just a 3rd-party assembly in my project

thick terrace
#

if it's not open-source and they don't produce a version that supports unity you're kind of out of luck unless you can find a way to modify it without source and also if that's not going to be a license/cert problem in your situation

tame anchor
#

I hear you, but while it is open-source, I don't love forking a popular assembly with frequent commits just for that reason...

fallow quartz
cosmic rain
#

Is a bit of a rough explanation that can deny some use cases. To have a full picture, you should learn what types/classes/structs are and what objects/instances are and the relationship between the them.

fallow quartz
cosmic rain
fallow quartz
#

That static makes the variable become a blueprint thing

#

And not the object itself

cosmic rain
#

Yes

fallow quartz
#

So methods will execute on the blueprint and change all of them

#

And without static just the object focused on

cosmic rain
#

Yes

fallow quartz
pulsar gulch
#

Hey guys
Is it possible to create a virtual webcam (like OBS, for example) that is separate from the main webcam and could display images from within the project/game?

Example: in the created virtual webcam, have a character from within the game displayed.

iron spade
#

hello, do someone have a great singleton base script ? thx

vagrant steppe
#

ChatGPT made me a Fully Working Stereo System with wireless speakers! Amazing! Every function fully works. But it sure did take talking to it like a crazy madgirl 🙂 This is for a VR Environment.

mild scaffold
#

Quick question, how do I format an if statement that checks for the scene that the player is currently in?

vagrant steppe
#

using UnityEngine;
using UnityEngine.SceneManagement;

void Start()
{
// Check if the current scene is "MainScene"
if (SceneManager.GetActiveScene().name == "MainScene")
{
Debug.Log("Player is in MainScene");
}
// Or check by build index (e.g., scene at index 1)
else if (SceneManager.GetActiveScene().buildIndex == 1)
{
Debug.Log("Player is in the second scene");
}
}

#

if you need the code

rigid island
#

congrats

vagrant steppe
#

however i get your point.

mild scaffold
vagrant steppe
vagrant steppe
mild scaffold
#

🤣

rigid island
vagrant steppe
rigid island
#

Also 99&% of the time, the code it throws at you is probably over convoluted and inefficient

vagrant steppe
#

i fixed it though

#

I know people will shoot me for using chatgpt but for the basic stuff its aight. 🙂

rigid island
#

most people don't care anyway, the project is yours. Do what you want, people just want to point out the drawbacks incase you go too deep in the rabbit hole without knowing how to code anything on your own once you get out

mild scaffold
#

worked, thanks for the help

#

overall question for yall, why dont you use unreal?

rigid island
#

because its not the right tool for my work

#

and C++ is frustrating

vagrant steppe
# mild scaffold overall question for yall, why dont you use unreal?

Learning it is unreal... literraly it is SO much more unnecessary complex compared to unity paint.exe atmosphear. Example in unity i can just change the color of objects by selecting a color. In unreal i got to add many vector points and a slider thing just to even think of changing a color.

rigid island
#

Unity gives you just enough and its clean interface,
Unreal is like stepping into a fucking alien mothership, they got buttons and windows scattered all over the place

#

and its also horrid for 2D. Its like trying to slice bread with a chainsaw

void basalt
#

its almost embarrassing

mild scaffold
#

🤣

vagrant steppe
#

I come home to relax not die in unreal lmao

mild scaffold
#

very interesting takes

void basalt
#

not to mention the absolute mess visual scripting becomes after making anything

rigid island
#

oh yeah if you use visual scripting is even worse.. so messy

vagrant steppe
#

Even GPT turns an eye from unreal lmfao

#

My current unity project is unbelievablty complex

#

chatgpt can only dream lmao

mild scaffold
#

what are you working on?

vagrant steppe
#

I am making an adventure game for children

mild scaffold
#

interesting

rigid island
#

!ask

tawny elkBOT
vagrant steppe
#

there is nothing to hide in this screenshot lol

#

Here is a screenshot of a baked scene.

shadow viper
#
public void OnInteractWithTV()
{
    if (isMazeGenerated)
    {
        
        int randomIndex = Random.Range(0, cornerObjects.Length);
        Vector3 teleportPosition = cornerObjects[randomIndex].transform.position;

       
        Debug.Log($"Teleporting player to: {teleportPosition}");

        if (teleportPosition != Vector3.zero)
        {
            
            playerController.enabled = false;  
            player.transform.position = teleportPosition;
            playerController.enabled = true;   
        }
    }
   
}

#
private void CreateCornerObjects()
{
    Vector3[] cornerPositions = new Vector3[4]
    {
        // 4 corners maze
        new Vector3(0, 0, 0),  
        new Vector3(mazeWidth * cellSize, 0, 0),  
        new Vector3(0, 0, mazeHeight * cellSize), 
        new Vector3(mazeWidth * cellSize, 0,     mazeHeight * cellSize) 
    };

    //creates obj
    for (int i = 0; i < cornerPositions.Length; i++)
    {
        cornerObjects[i] = Instantiate(cornerObjectPrefab, cornerPositions[i], Quaternion.identity);
        cornerObjects[i].name = "CornerObject_" + i;  
    }
}
rigid island
#

this is going to be a mess if you do piece by piece

#

⬇️

tawny elkBOT
shadow viper
#

ehhh ill post it to github

rigid island
#

actually nvm lol Goodluck bud

shadow viper
rigid island
shadow viper
cosmic rain
#

I don't see any question or description of the issue..? Did you post your code just for people to read it?

daring pine
#

Yo i need help i have 2 triggers one for coke and one for cake and i have 4 ui text 1 bro before and after one mom before and after so i want to make the mom before disable and after enable if it detects cake trigger in the console and if it detects coke trigger do the same with bro

soft dome
#

can anybody tell me if OnBecameInvisible() happens reliably every time that OnDestroy() does?

#

so when an object on screen is destroyed, both always get called?

#

and if so, in which order?

thin aurora
#

So no, looks like they don't need help

#

No idea what just happened anyway but I think I'll ignore any messages from them from now on

buoyant vault
#

Hello, im trying to make an ability system. Currently I'm using scriptableObjects. My problem is I can't think of a way to handle dependencies. Each ability will have their own dependencies. Ex: Ability1 might need to reference player. But Ability2 might need to reference a sprite or a prefab.

plucky inlet
thin aurora
#

You could make a general context object and pass those into the SO. These work by reference so you can place everything in this like a bag

buoyant vault
thin aurora
#

Or does this depend on other things?

winter valve
#

how 2 make 2d objects clickable? only througth button conponent?

buoyant vault
plucky inlet
#

As your behaviour is so different between all those abilities, I am not sure, if you really can squish that into one big SO handling all those behaviours. Of course, you could inherit and just overwrite, but what would be the matter then having SOs the first place. I think, best bet would be to really write down all your abilities and then start to shrink down the most common things in them and how they connect to your gameplay/player.

sleek bough
tawny elkBOT
#

dynoSuccess nameless37.6 has been warned.

plucky inlet
plucky inlet
# winter valve i mean 2d ui

Then yes, its a button usually. I mean, you can also raycast against those, as you can see the Raycast Target option on images too. What are you struggling with?

buoyant vault
plucky inlet
plucky inlet
winter valve
#

y does this row make nullptr exception?

offset = transform.position - window.transform.position;```
winter valve
#

oh, yeah

#

i have script like this

//libs

public class DragField : MonoBehaviour
{
    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("Drag");
        transform.position = eventData.position;
    }
}```
but when i drag nothing happens. even it doesn't logs
soft dome
#

eg. public class DragField : MonoBehaviour, IDragHandler

winter valve
#

thx

placid summit
#

After the latest VS update the unity monobehaviours are marked unused which is annoying! I rebuilt the C# solution

knotty sun
placid summit
knotty sun
#

tbh it's not a code problem at all so does not belong in any code channel

trim schooner
placid summit
#

yes but not sure another place to post - anyway discussion was useful

soft shard
winter valve
#

how 2 make some action happening on click on object with specific button?

dusky lake
winter valve
vagrant blade
#

Whatever you're doing to make it happen with one action, do it again for the second one

rigid island
winter valve
vagrant blade
#

No, if you're calling something inside the OnMouseDown, call another thing in there too

rigid island
#

or OnMouseDown works too but less reliable

winter valve
#

u don't understand my question

#

i mean, i have metho like this:

private void OnMouseDown()
{
    if (Input.GetMouseButtonDown(1))
    {
        Debug.Log("uuuuuuuuuuuuhhh");
    }
}```
#

but when i click on rbm nothing happens

rigid island
winter valve
#

yes

rigid island
#

is it a trigger?

winter valve
#

yes

rigid island
winter valve
#

oh, it doesn't trigger on rbm

rigid island
rigid island
#

just need to put a Physics Raycaster on the camera and add new Event System gameobject

winter valve
#

now it never triggers

rigid island
# winter valve idk how

wdym you dont know how, i just told you how lol add those components and there is an example script. There isn't much to it..

winter valve
#

when i click nothing happens

rigid island
#

and then you dont add GetMouseButtonDown, thats is only used for Clicking in general not a specific item

#

and the function would look like

  public void OnPointerClick(PointerEventData pointerEventData)
    {
        Debug.Log(name + " Game Object Clicked! " + pointerEventData.button);
        if (pointerEventData.button == PointerEventData.InputButton.Right)
        {
            Debug.Log("Right Button Pressed");
        }
    }```
winter valve
rigid island
#

you show me wrong code again and not the components i asked to see

#

again:

  • Camera must have a Physics Raycaster component
  • the heirarchy must have at least 1 EventSystem gameobject / component
winter valve
#

thx

rigid island
#

did you get it working?

winter valve
#

at least it calls

rigid island
#

ok so copy the rest of what i wrote

winter valve
#

& it works

rigid island
#

GetMouseButtonDown in there is not valid

winter valve
#

thx

solemn ember
#

hi chat

#

I'm making a deck editor, well.. it's done already

#

on webgl, and currently I export to .TXT, which is nice

#

and this is what the exported file looks like

#

however, I was wondering if I can export things as .png

#

or pdf

#

so instead of my text, I can export something that looks like this

rigid island
#

png yea. pdf you might need library

#

png you just screenshot what the camera sees basically and save the texture as file encode to png

vestal arch
#

fwiw if you want to import that result somewhere you should maybe consider using json or yaml so there's more of a defined structure

#

(or, god forbid, xml)

solemn ember
#

whatever is not super complicated

vestal arch
#

none of them are complicated

solemn ember
#

any guide on that?

vestal arch
#

they're just ways to relyably, safely transfer data

rigid island
#

basically use ToJson

vestal arch
#

you won't need to (and shouldn't) implement the encoding yourself either, libraries exist for them, and for json, c# has a built-in parser/stringifyer

solemn ember
#

yeah

#

how do I do them

#

XD

solemn ember
#

okay... now

#

would you guys like to... help me deeper with this? or the guides should be enough

rigid island
#

btw lookup PDFsharp seems to be good .net library

vestal arch
#

data encoding is a pretty general topic, there's tons of resources online for them

#

try googling to understand json to start, maybe?

solemn ember
#

I will make a new script, call it "ImageExportManager.cs"

solemn ember
#

have a camera that takes a screenshot and export that

rigid island
#

thats the most basic way to save what your camera sees yes, its up to you how you arrange that UI for export

solemn ember
#

yeah, with this method I was thinking of making a new "Scene" per say

#

with a layout for this

#

Well thanks for that, I'll prepare everything when I get home and then when I get to that image export part I'll be back

solemn ember
#

That's something to worry later? It looks like it's just formatting

vestal arch
#

and json/yaml/xml are kinda self-documenting as well, since you can use keys to define what each value is easily

bold fulcrum
#

Is there a way to download mesh data from the gpu so i can access it, without having to enable isreadable

vestal arch
#

have you tried googling them

solemn ember
#

yes

#

I googled it, there's a lot

#

Idk what I should look at

#

rather, I would just do this... not learn the whole thing for now

#

I don't want to expertise in a topic by studying, rather by doing what I need

#

if I need to do it often I will learn each aspect of it eventually

rigid island
#

json is a pretty important, comon format you will probably be working often in the future

solemn ember
#

I know json binary formatter

#

I use json in this project

#

but it has no use on images, I think ?

vestal arch
#

right, i just mean if you want to be able to import it later

solemn ember
#

ohhh

rigid island
solemn ember
#

thx, yeah I do use it for that

#

I let people save as json

#

to be able to import them

#

that's already there

#

I'm trying to do images tho

#

so people can share them on the game's discord

#

which, is a cards game

knotty sun
#

you can actually save image data in json btw

solemn ember
#

I would like the decks to be shared in a visually pleasant way

#

in png images, that would look kinda like this

#

I made this layout for it, I gtg but when I get home I'll try the camera screenshot to then save

rigid island
#

is that how you want it arraigned all you need to do is capture the camera into png

solemn ember
#

yup

solemn ember
#

I'm testing ideas for the layout

rigid island
#

are you using UIToolkit ?

vestal arch
#

out of my own curiosity, if the intended export layout isn't the same as what's shown to the user live, would it make more sense to have a separate camera with the export layout just for that, or to use image processing?

solemn ember
#

I will have a different camera for the export layout

#

it's a different scene pretty much

solemn ember
high condor
#

i have been using a few sprite shapes to act as clouds in my game, but for some reason, one of the clouds cuts off and i dont know what to do to fix this

shrewd tendon
#

is there an easy way in C# to load a json file in a dict like structure similar to python or javascript?

eager tundra
#

I think that would be more like using JObject, but still with newtonsoft

shrewd tendon
eager tundra
#

it works pretty much like a Dictionary<string, JObject>

shrewd tendon
#

@Tupi Thanks I think that is exactly what I was looking for

#

It doesn't appear in the package manager under window...

#

got it!

upper pilot
naive swallow
upper pilot
#

Thats something I found on a youtube and wanted to be sure that I am not crazy.
I thought that coroutines keep running even without a variable

naive swallow
#

Reassigning the variable just changes which Coroutine that variable refers to

upper pilot
#

yeah thats what I thought, so it definitely needs to be stopped

north shore
upper pilot
#

Otherwise your healthbar might jump around

spare dome
glacial gull
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using TMPro;

public class PlayerSetup : MonoBehaviour
{
    public Movement movement;
    public GameObject camera;

    public string nickname;

    public TextMeshPro nicknameText;

    public Transform TPWeaponHolder;

    private PhotonView photonView;

    public void IsLocalPlayer()
    {
        photonView = GetComponent<PhotonView>();
        TPWeaponHolder.gameObject.SetActive(false);
        movement.enabled = true;
        camera.SetActive(true);
        Debug.Log("Local player set");
    }

    [PunRPC]
    public void SetTPWeapon(int _weaponIndex)
    {
        foreach (Transform _weapon in TPWeaponHolder)
        {
            _weapon.gameObject.SetActive(false);
        }

        TPWeaponHolder.GetChild(_weaponIndex).gameObject.SetActive(true);
    }

    [PunRPC]
    public void SetNickname(string _name)
    {
        nickname = _name;
        nicknameText.text = nickname;
    }
}

Hey guys ive been trying to make a multiplayer game. However, I kind of messed up when there are multiple players. The IsLocalPlayer() function was called but doesnt seem to be working. Can anybody help?

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class RoomManager : MonoBehaviourPunCallbacks
{
    public GameObject player;

    public static RoomManager instance;

    [Space]
    public Transform[] spawnPoints;

    [Space]
    public GameObject roomCam;

    [Space]
    public GameObject nameUI;
    public GameObject connectingUI;

    private string nickname = "Player";

    [Space]
    public string roomNameToJoin = "test";

    [Space]
    public Health health;

    [Header("UI screens")]
    public GameObject home;
    public GameObject homeScreen;
    public GameObject roomSelect;
    

    private void Awake()
    {
        instance = this;
    }

    public void ChangeNickname(string _nickname)
    {
        nickname = _nickname;
    }

    public void JoinButtonPressed()
    {
        Debug.Log("Connecting...");
        PhotonNetwork.JoinOrCreateRoom(roomNameToJoin, null, null);

        nameUI.SetActive(false);
        connectingUI.SetActive(true);

        Debug.Log("JoinButtonPressed() finished running");
    }


    public override void OnJoinedRoom()
    {
        base.OnJoinedRoom();
        roomCam.SetActive(false);
        Debug.Log("Connected: Room found");

        SpawnPlayer();
    }

    public void SpawnPlayer()
    {
        Transform spawnPoint = spawnPoints[UnityEngine.Random.Range(0, spawnPoints.Length)];
        GameObject _player = PhotonNetwork.Instantiate(player.name, spawnPoint.position, Quaternion.identity);
        _player.GetComponent<PlayerSetup>().IsLocalPlayer();
        _player.GetComponent<Health>().isLocalPlayer = true;
        _player.GetComponent<PhotonView>().RPC("SetNickname", RpcTarget.AllBuffered, nickname);
        PhotonNetwork.LocalPlayer.NickName = nickname;
        Debug.Log("Respawned player");
    }
}

north shore
#

instead of doing a regular void method, replace it with a bool method

#

oh no

#

wait

#

you should add an onInstantiate (if that exists, you might need to do a MonoBehaviourPunCallbacks on playersetup instead of MonoBehaviour), then call the functions you did in spawn player (after PhotonNetwork.Instantiate) in that onInstantiate Function

#

but if (photonView.IsMine)

north shore
#

with the same steps

glacial gull
#

ill try that 👍

glacial gull
north shore
#

but try start if that does not work

glacial gull
#

ok

#

I dont think any of the solutions are working?

upper pilot
glacial gull
north shore
#

what does your code look like

glacial gull
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using TMPro;

public class PlayerSetup : MonoBehaviour
{
    public Movement movement;
    public GameObject camera;

    public string nickname;

    public TextMeshPro nicknameText;

    public Transform TPWeaponHolder;

    private PhotonView photonView;

    void Start()
    {
        if (photonView.IsMine)
        {
            GetComponent<PlayerSetup>().IsLocalPlayer();
            GetComponent<Health>().isLocalPlayer = true;
            GetComponent<PhotonView>().RPC("SetNickname", RpcTarget.AllBuffered, nickname);
            PhotonNetwork.LocalPlayer.NickName = nickname;
        }
    }

    public void IsLocalPlayer()
    {
        photonView = GetComponent<PhotonView>();
        TPWeaponHolder.gameObject.SetActive(false);
        movement.enabled = true;
        camera.SetActive(true);
        Debug.Log("Local player set");
    }

    [PunRPC]
    public void SetTPWeapon(int _weaponIndex)
    {
        foreach (Transform _weapon in TPWeaponHolder)
        {
            _weapon.gameObject.SetActive(false);
        }

        TPWeaponHolder.GetChild(_weaponIndex).gameObject.SetActive(true);
    }

    [PunRPC]
    public void SetNickname(string _name)
    {
        nickname = _name;
        nicknameText.text = nickname;
    }
}

north shore
glacial gull
#

let me just run it to try it again

glacial gull
north shore
north shore
glacial gull
#

oh ok

north shore
#

like your move script

glacial gull
#

Now the player can only move once another player has joined...

north shore
#

because I do not know how this is all being handeled

glacial gull
#

actually, i have looked up some pun tutorials and my game was working pretty well until i added some grenades. I disabled everything new that i added, however its just not working now and i have no idea why

north shore
glacial gull
north shore
glacial gull
#

nvm, i think its fixed now. I removed the if (photonview.ismine) and everything is as intended

shrewd tendon
#

I have a bunch of letters that you should be able to click individually, but when I try to click them I get the handler of adjacent letters

#

any ideas on how to fix this?

leaden ice
shrewd tendon
#

I already figured it out

#

I had to change the sizeDelta of the rectTransform

#

I have a vague idea why it worked

#

I set the click handler on a GameObject that contained a TextMeshPro with a single letter

#

I suspect that the sizeDelta created this geometry around the GameObject that made it clickable. This geometry exceeded the individual letters sufficiently to overlap with the other letters.

#

Are my assumptions correct? And if so is there some way to learn a bit more about this?

#

Any keywords to find more information?

rustic ember
#

How would I get the width of this rect tranform?

vestal arch
rustic ember
vestal arch
#

you can't since it's set to stretch to fill its container

rustic ember
#

I actually just want to set its "Right"-value

vestal arch
#

anchorMax maybe? im not sure

rustic ember
#

Actually, I just found a thread. cs offsetMax Is what I'm looking for

vestal arch
#

yeah was about to say lol

rustic ember
#

I am lost. I need the number of pixels it takes up on the x-axis

#

The amount that it is stretched

vestal arch
#

pretty sure it's that

tawdry jasper
#

Allegedly in unreal you can "enable physics" on parts of a model skeleton, getting "partial ragdolls". Do you think there's a way to achieve this in unity? (Like playing a walk cycle with a ragdolled "limp" arm?

(An idea I never got working, when I tried to make an "active ragdoll" would be to have an unskinned skeleton playing animation and manually copying over rotations to a skinnedmesh skeleton, omitting parts of a model. Another might be setting up a limp arm ragdoll and using it as an IK target for the IK animation rigging?)

cosmic rain
#

The important point to note is that the animator usually updates the bones later in the frame(after regular update), so you need to update the bones even later if you want to override it. LateUpdate usually happens after the animator update.

void basalt
#

you'll need to find a way to keep the animation from resetting the limb transforms

flat marsh
#

Are there any naming conventions I should use for my code? Up until this point I've just used names that semi fit the functions of that variable, however, I may soon have others looking at my code and I dont want it to appear random. Are there any naming conventions I should know about?

tawdry jasper
lean sail
hidden stratus
#

Hello, I have a basic camera setup with 3d orthographic projection so that it is pixel perfect (no pixel perfect = jittery camera) - it snaps to the pixels u can see in the video.
Im trying to get the camera to be smooth by making it subpixel, does anyone know the best way to do this? or the way that it will look the smoothest?

I tried doing it by making the camera output to a render texture then I use a raw Image to display it and I used the UV Rect to offset in the X and Y (subpixel) - This should technically work and it kinda does but it jitters often especially when moving the camera diagonally.

neat cloud
#

I have all the code finished. I’ve added in-app purchases, and they work in my internal testing build. Reward ads are also implemented and work fine in the editor, but in my internal build on Android, the AdsInitializer doesn't work. Using Logcat, I see an error:
ClassNotFoundException: com.unity3d.services.banners.IUnityBannerListener.

Since I don’t use banner ads and can’t find anything in my code trying to access them, can anyone help?

stone arch
#

my ball doesn't come back down when i make it jump, any common fixes?

#

i have gravity ticked on the rigidbody

mellow sigil
#

Show the code for jumping and movement and you'll get the actual fix instead of blind guesses

stone arch
#

I use Playmaker

mellow sigil
#

Ask on the Playmaker server then

stone arch
#

ok, thanks

karmic herald
#

anyone have a way to like, get one indice out of an array, set that one active, and set all the others false?

#

cuz the way im doing it (for loop sets all objects inactive, then set individual active) doesnt work

vestal arch
#

that's how you do it

#

how isn't it working?

karmic herald
#

sry to specify im trying to flip the active state but it only sets the one im choosing active, doesnt deactivate

for (int i = 0; i < items.Length; i++)
        {
            items[i].SetActive(false);
        }
        iname = transform.GetChild(1).GetComponent<Text>().text;
        if (iname == "Longsword")
        {
            items[0].SetActive(!items[0].activeSelf);
        }
knotty sun
#

why [0] ?

karmic herald
#

i have if statements for each indice, i just didnt feel like making the message take up more space

vestal arch
#

a dict would make that much easier to manage

karmic herald
#

ive never heard of those :0

knotty sun
#

that code makes no sernse as it is

vestal arch
karmic herald
#

ya im looking at unity doc rn

#

ty for tellin me

vestal arch
#

it's not a unity thing

karmic herald
#

well yea but unity has a page on it

robust dome
#

what would be the best and most solid soloution if i have a parent gameObject that highly depends on child transforms. i thought about using GetChild but then enduser might be adding more child objects so the order would break. i could use the name of the child objects whihc is also not the safest method. would creating direct references be a good soloutoin but again the risk that all the field get empty when something bad happens is to high. what would you do in this case. it is for an asset so any game dev can use in their project

#

the parent object needs to take care of the ui system so the child objects are in fact ui elements i forgot to add

leaden ice
#

No idea what risks you're talking about

#

It's in fact the least risky option since it is resilient to hierarchy modifications

robust dome
#

so direct references would be safest

leaden ice
#

"safest" is a vague term

#

It should be your go to in most situations

robust dome
#

i was also tending to this method , i really hope the fields keep the reference. i remember for some reason a few years ago when something bad happend and i came back to the project all fields were empty

#

i can´t remember exactly what caused this

#

thanks for confirming this Praetor.

#

i think this is for now the only soloution to use

grand brook
#

hellooo, this is a programming and physics question, and since im new to programming I feel its better to post here.

Im trying to rotate a Rigidbody2D with add torque, and CounterAct it with a counter torque. My problem is that, the if statement on the update method just, doesnt do anything? The debug changes on the console, but nothing happens

    private void Update()
    {

        float angularVelocity = PlayerRb.angularVelocity;
        if (angularVelocity > 0.0001)
        {
            PlayerRb.AddTorque(angularVelocity * dampening);


        }
        if (angularVelocity < -0.0001)
        {
            PlayerRb.AddTorque(angularVelocity * dampening);
        }

        Debug.Log("angularVelocity " + angularVelocity);

    }

    public void CanRotateRight()
    {
        if (CanMove == true)
        {


          //transform.Rotate(-Enhance.playerRotation * Time.deltaTime * transform.forward * 4);
            PlayerRb.AddTorque(-Enhance.playerRotation  * 400);
            
            Debug.Log("Is rotating right");

        }
        //PlayerRb.AddTorque(-Enhance.playerRotation );





    }
    public void CanRotateLeft()
    {
        if(CanMove == true)
        {

           // transform.Rotate(Enhance.playerRotation * Time.deltaTime * transform.forward * 4);
            PlayerRb.AddTorque(Enhance.playerRotation * 400);
        }

        //PlayerRb.AddTorque(Enhance.playerRotation );






    }```
#

My idea to counter act the torque is to grab teh angular rotation and mutiply by a variable. When it detects it is rotating to one side it will addTorque to the other side

#

I changed and add "-" signs to everything on my update method but nothing works or changes

#

I placed my dampening varaible on the millions and on the nanometers and still nothing

mellow sigil
#

To start with, AddTorque should be applied in FixedUpdate instead of Update. (It's not causing the actual issue though.)

#

You have a lot of other rotation code there so I suspect you've just forgotten to comment out one somewhere else

grand brook
#

hm... I have nothing else that is changing the rotation or setting it back to its original state

somber tapir
#

The player moves the mouse to the blue dot, holds down the left mouse button and drags it to the right. The further it is dragged from the start position the more force is applied once the player releases the key, like a simple billiard game.

From this angle I can simply check the distance of the x positions of the mouse position and the position of the mouse when the player started holding the button.

But how would I calculate it if the player aims from the left or from 65°?

tame lance
#

Im trying to repair some really old code, and Im having trouble with an asset call.
Ive verified that Assets/Resources/Atlases/hd2/masks+hd2.tk2d exists..
During runtime, I indeed verify its asking for the string Atlases/hd2/masks+hd2.tk2d... and yet the system says the resource doesnt exist.
it fires an error at the string array split line near the end, saying that the resource doesnt exist. The LogWarning I put there also results in "null"

vestal arch
hexed pecan
tame lance
swift falcon
#

Does anyone have any experience with "Active Rigidbodies"?
~ I'm trying to make a custom one or at least modified one from Ragdoll Animator 2 or Final-IK Pro, but I could use some help outlining the code structure.
++The Goal is to create a FallGuys/HumanFallFlat wobbly body (but even more wobbly) with a Balance & Falling mechanic if the player leans too far in one direction or trips on a curbside they fall in a really silly way and get back up after a few seconds. The challenge is the player movement, getting from point a to point b

Would be easier to explain in voice or stream or send a screen recording, so if you have any experience with Rigidbody Movement + Ragdolls please let me know.

I made some prototypes, but am struggling to get it to the desired gameplay behavior.
• The ragdoll/animation blends, can't get him to properly trip on the curbside.
• Movement & Tilt controls, having trouble putting the pieces together in my head (if that makes sense)?
• Not sure how to implement the Tilt/Balancing feature ~ I know how I want it to look, but not how to structure the code.
• Having difficulties with muscle-strength & wobbly-ness balancing in the inspector. Either too floppy or not floppy enough. Can't figure out how to add joint constraints.

Once to get this Active-Rigidbody PlayerController code is figured out the rest should be simple BlobAww

(sorry long msg, dont read it if it makes ur brain go "ouch!") blobsweat

spare dome
# swift falcon Does anyone have any experience with **"Active Rigidbodies"**? ~ I'm trying to m...

do you mean active ragdolls? If so all they do is they copy animations or use "pulling" forces to make any type of movement, human fall flat just locks the hips so they can never fall down as a balancing force, what you can do instead is try and make the hips rotate to a certain rotation so it has the ability to fall down and such (if the logic is coded in of course)
here is a good video explaining the active ragdolls and what they do and how they act
https://www.youtube.com/watch?v=HF-cp6yW3Iw&ab_channel=SergioAbreuGarcía

This is all I learned while making active ragdolls in Unity. I hope you find it useful or, at least, interesting :D

The actual tutorial: https://bit.ly/3lKsfk2
Github repository: https://bit.ly/2VxnU98

----- Social -----

Twitter: https://twitter.com/sergioabreu_g


Ambient Generative Music by Alex Bainter [generative.fm]

-...

▶ Play video
swift falcon
# spare dome do you mean active ragdolls? If so all they do is they copy animations or use "p...

Yeah, sort of. But not exactly. I used it as an example because a lot of people don't know what "Active Ragdoll" means. It's the floppy body movement.

In my player controller, I'm not doing a FallFlat or FallGuys style game. In mine, I am trying to figure out how to blend the Animations + Active Ragdoll + Rigidbody & Tilt Movement.

Imagine tilting your mobile phone to try to keep a drunk guy balanced walking down the street, and falling over knocking over trash-cans, getting hit by cars and ragdoll-flying, tripping on the curb, or falling if the player can't keep you balanced.

The body & animations & ragdoll & feet-ik & tilting all have to magically come together to make the drunk guy look good. (doesnt have to be super realistic, just good controls feedback and funny physics & animations)

#

I managed to get the active ragdoll & floppy body movement, it's tweaking it to look good and adjust the legs/feet, spine, etc looking right where I'm struggling
+And I haven't even figure out how to implement the tilt and extra drunk animations, or switch to goofy sort of involuntary movements

#

++I was thinking about adding 4 spheres with colliders (invisible) around the top or mid section of the ragdoll-player and using those to push the player.

#

for movement

#

but it wouldnt be as smooth as trying to figure out how to add force to the bone directly

#

I tried that but Ragdoll Animator 2 said Nope.

untold brook
#

! Learn

#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

spare dome
# swift falcon Yeah, sort of. But not exactly. I used it as an example because a lot of people ...

you would probably just want to start off by saying "active ragdolls" instead of "active rigidbodies" as that makes no sense, like I said you would want to use animations or forces on the limbs rigidbodies to make movements, to implement your falling over and stumbling you would want to make the hips try and rotate to a certain orientation using forces but not lock it entirely so your active ragdoll can be floppy and can fall over, you would most likely want to use forces or procedural animations with IK to get this sort of effect, it solely depends on what you want to do though. Then using this you can add the procedural tilting by just adding a rotational force to the hips to make them wobbly and such. here is another video to explain the forces side of active ragdolls
https://www.youtube.com/watch?v=hQub6caVlpY&ab_channel=BirdmaskStudio

swift falcon
#

@spare dome Omg.. *facepalm
"adding a rotational force to the hips" I was not adding rotation-force when I tried. That might fix the issue.
Thank you. ♥

rain igloo
#

I have a question. Right now I am having a problem with animations. It's a 2d top down view game, and i can walk forward and that animation plays. same with going to either side. but going down is not working. like there is just no animation that plays. I've spent a while trying to figure it out and can't find a way around it besides rewriting all of my code

vestal arch
#

you sure you haven't just misconfigured animations?

rain igloo
#

yea, i've set it up in the animator. i just can't find a negative modifier to make the animation activate

vestal arch
#

wdym

rain igloo
#

i have it setup so if my y goes positive, the forward animation plays. Then if the Z goes positive it plays, and negative it plays but flipped. That won't work for the forward animation, and I can't figure out how to make it a similar function, but with the workaround of different animations. Rather than flipped

vestal arch
#

alright, how do you have it set up currently

rain igloo
vestal arch
#

!screenshot

#

oh that command is for a different server i guess

#

!code

tawny elkBOT
vestal arch
#

anyways though; you can't just set up another animation state with the opposite transition?

rigid island
spare dome
#

most some of the bot commands only respond the plural pronunciations

rain igloo
vestal arch
#

ok so why not use fSpeed as a velocity instead and use y directly
that way you can make a transition based on whether it's positive or negative

rain igloo
#

that worked, thanks for the help

faint hornet
#

can someone tell me why the "MoveAllDice" function works when called by itself, and the " TaskChain" doesn't work at all. no errors. all debugging shows data is there. idk whats happening

  {
    Vector3 start = trans.localPosition;
    Vector3 end = trans.localPosition;
    start.y -= 500f;

    Coroutine routine = null;
    CreateRoutine(TransformUtility.LocalPositionRoutine(trans, curveDiceMove, start, end, 1f), routine);
  }

  public IEnumerator TaskChain(float iterationDuration)
  {
    float et = 0;
    int i = 0;
    while (i >= diceComponents.Length)
    {
      et += Time.deltaTime / iterationDuration;
      if (et >= iterationDuration)
      {
        MoveAllDice(diceComponents[i].transform);
        i++;
        et = 0;
      };

      if (i >= diceComponents.Length) break;

      yield return null;
    }
    yield return null;
  }```
leaden ice
faint hornet
#

i'm running it in "Start()"

leaden ice
#

how?

#

show the code

faint hornet
#
  {
    StartCoroutine(TaskChain(1f));
  }```
leaden ice
#

ok so what do you mean by it not working at all?

#

Did you try putting Debug.Log in it?

faint hornet
#

nothing happens.

#

yes

leaden ice
#

And?

#

Does it run?

#

Where did you put the log?

faint hornet
#

i've tried the log in many places. it works everywhere and when i check transform[] data it's there.

leaden ice
#

while (i >= diceComponents.Length)

MoveAllDice(diceComponents[i].transform);

#

This seems guaranteed to be an error

#

i.e. ArrayIndexOutOfRange error

#

or more likely

#

it just won't enter the loop

#

becaquse 0 is not >= diceComponents.Length

faint hornet
#

logging the length it's 6

leaden ice
#

ok so yeah

#

0 is less than 6

#

so the while loop will be skipped entirely

faint hornet
#

omg. it's supposed to be <= ?

leaden ice
#

< unless you want an error... But yeah basic logic dictates that.. no?

#

Think about it

#

Why not just a regular for loop btw

faint hornet
#

because of the delay

leaden ice
#

What about it

#

What does the delay have to do with for vs while

#

Wait with this:

      et += Time.deltaTime / iterationDuration;
      if (et >= iterationDuration)
      {
        MoveAllDice(diceComponents[i].transform);
        i++;
        et = 0;
      };```
Are you trying to wait for the one die to move before continuing?
#

Why not just yield the coroutine for that single die moving?

#

the way you have it now it seems you'll create a new coroutine each frame

swift falcon
broken mantle
#

I have a question:
when setting a few things I used playerprefs to give them values right before building. do those values get carried away to the build or is there a save file in unity data that those values stay in and don't effect the build.

knotty sun
broken mantle
#

I see thank you

#

so if I used a if statement with a playerpref condition it gives a null?
in that case does the if statement work or no

knotty sun
#

you really should refer to the documentation for questions like this

robust dome
broken mantle
#

I see

#

thank you guys again

lapis badger
soft shard
prime lintel
#

May I check if this is how I should use a LayerMask with Raycast? I am specifying my Player and Map layers for mob vision.

Collider2D[] targetColliders = Physics2D.OverlapCircleAll(m_mob.transform.position, m_visionRadius, m_targetLayers);
if (targetColliders.Length > 0)
{
    LayerMask raycastMask = m_targetLayers | m_obstacleLayers;
    foreach (Collider2D collider in targetColliders)
    {
        RaycastHit2D los = Physics2D.Raycast(
            m_mob.transform.position, 
            (collider.transform.position - m_mob.transform.position).normalized, 
            m_visionRadius,
            raycastMask);
        if (los.transform != null)
        {
            //if (los.collider.gameObject.layer != m_targetLayers) continue;
            Debug.Log(LayerMask.LayerToName(los.collider.gameObject.layer));

            // If in LOS, add or update dictionary
            float dist = Vector2.Distance(m_mob.transform.position, collider.transform.position);
            collider.transform.TryGetComponent(out FriendlyUnit unit);
            if (unit != null)
            {
                if (m_trackedTargets.ContainsKey(unit))
                {
                    TrackedData data = m_trackedTargets[unit];
                    data.distance = dist;
                    data.found = true;
                    m_trackedTargets[unit] = data;
                }
                else
                    m_trackedTargets.Add(unit, new(dist));
                res = true;
            }
        }
    }
}

When I run this, all I get are rays that collide with the map, despite my player being in direct line of sight from the origin of the mob's transform. Am I misunderstanding how to provide the LayerMask argument for Raycasts?

somber nacelle
#

rather than just printing the layer that is hit by the raycast, you should print more information like what was hit, maybe what object and position the ray originated from, and probably also draw the ray so you can visualize it and see why it may not be hitting what you expect it to

#

BaseState likely does not inherit from MonoBehaviour so it does not have a GetComponent method. it also wouldn't make sense to call GetComponent on an object that isn't even attached to a gameobject. you need to call GetComponent on that gameobject or one of its components. perhaps the stateMachine which appears to be a monobehaviour

#

also get your !IDE configured

tawny elkBOT
somber nacelle
#

if only there were a big bot embed directly after my message that would give you some hint

#

reading must be hard, huh?
you are expected to configure your IDE, if you don't know what "IDE" stands for you can simply google it. or literally look at the list of IDEs the bot message has

#

this is the general code channel, you are expected to have at least some knowledge when asking for help in here. even if we were in the beginner channel you are still expected to actually bother reading the information provided to you instead of ignoring it and expecting everyone to wait on you hand and foot because "i'M a bEgInNeR" or whatever

spare dome
#

alright play nice now, IDE (integrated development environment) is what you code in, VS and VSC (with extensions) is an IDE

somber nacelle
#

again read the information presented to you. google things you don't understand.

#

that's okay, i don't plan to help people who put zero effort into getting help anyway

vestal arch
#

my guy if we don't use the assumptions of prior knowledge then 80% of the channel would be explaining simple terms that can and should be googled
because google has better answers than us

#

"ide" is a coding thing, not a c# thing

#

and... yeah i assumed you had issues, that's why most people come here
that's not what im talking about

prime lintel
somber nacelle
#

do that now and print more info about what they are hitting

prime lintel
vestal arch
#

what i mean is, you gotta understand that we, as helpers, have assumptions about what askers know before asking. we generally assume based on what is asked, and also assume a base level of knowledge. if you, as an asker, don't have that assumed base knowledge, you can't just treat it like something super advanced because you don't know it
pretty much everything we talk about here has resources on it on google. very good resources. better than we can provide, because those resources have been thought about and improved over months or years

the internet is a very important tool. you gotta learn to use it. it's much faster and better for general stuff than us. only for questions where online resources are insufficient, outdated, conflicting, or confusing, should you ask us.

somber nacelle
prime lintel
#

Could it be my map collider set improperly?

somber nacelle
#

so then your raycast is hitting your map

prime lintel
#

It's currently using these settings

#

Could I have made an error with setting up its collider? It cant be that the collider spans the entire scene right?

somber nacelle
#

are you certain that is not the case? i've not seen your scene setup so i couldn't answer that

prime lintel
#

I apologise, I am new to unity so I am not too sure what is the correct way to setup tilemap colliders

#

Is there anything you can recommend?

somber nacelle
#

i don't know anything about your scene except for the one screenshot of your tilemap collider you've shown. as a result, i have no recommendations because i don't know what you have or have not done. i don't know if you have done something silly like put all of the tiles on a single tilemap and just expected the background tiles not to have collisions, i don't know if maybe you have invisible tiles all over the place

#

there are too many unknowns here for me to make any sort of guess as to why your raycast is hitting your map, other than the fact that the raycast is hitting the map's collider

vestal arch
#

make sure layers are set up correctly?

prime lintel
somber nacelle
#

print some more useful information rather than just the position of the object hit and its layer. print where the hit actually was, the actual name of the object hit, maybe even the origin of the raycast so you can see all of this information instead of making assumptions

prime lintel
#

Does this mean I have to compensate for an offset when it comes to providing the vector positions of my casts?

somber nacelle
#

if it is a sprite renderer then where it appears is dependent on its pivot point set in the sprite editor

prime lintel
#

It seems to originate from the center of my mob though

#

oh my goodness

somber nacelle
#

if you select your object and set your tool handle to Pivot instead of Center you'll see where it's actual pivot point/position is

prime lintel
#

i used the built-in aseprite extension and it seems there are custom pivots with some crazy values for all frames

somber nacelle
#

looks like the sprite you have selected there has a pivot point below the actual sprite. i would recommend just moving its collider to a separate object and adjust it so its center is the center of your object

prime lintel
#

is there a way to simply ensure the collider's transformation position is the same as the object's center?

somber nacelle
#

yes, just put the collider on a child object and move that object so that it is centered on the object which is what i just recommended

prime lintel
#

my mob still seems to have a foot fetish 😭

somber nacelle
#

this object's position is still 0,0. you've adjusted the center of the colliders rather than the actual position of the object they are attached to

#

if you need 3 separate colliders, then you'll likely want 3 separate objects, one for each collider. then leave their center property at 0,0 and just move the child object so it is in the correct position

prime lintel
#

I see, so I should ensure the offset is all 0 and they are assigned to individual objects and use those objects to position the colliders

#

Is that correct?

somber nacelle
#

yes, that way their transform.position will be the actual center of each collider

prime lintel
#

I understand now! I'll have to continue this in the morning, its 4am rn. But thank you so much for your patience and time! If its possible I'll update you whether I manage to get it working

#

thank you so much

left gale
#

So I have only seen the project setup/organization used by a single (full, shipped) unity game. And therefore I am unsure if this setup is unusual or not, but ..

Q: Do people tend to really use assembly definitions and have all their code files under assets? And conversely, is having gameplay code within separately built regular class library projects very unusual?

The unity game I looked heavily into and did modding for, and contributed code to also, was setup such that the player project itself had almost nothing in it. The games code was all in regular C# class library projects (which referenced unity dlls) and then those assemblies were post-build copied into an Assets folder (or otherwise ended up being loaded/referenced at runtime).

The reasons I believe it was setup this way ...

  1. assembly definitions may actually not have existed at the time this game was started
  2. every line of gameplay code changed doesn't become something that must be rebuilt with the editor, the runtime code is capable of reloading the changed assembly live without relaunching it
  3. for modding support, where mods can contain either modified versions of them, or can put new assemblies in the correct folder to get modded-code to run
  4. a strong effort was made to isolate the unity-specific code from the actual gameplay code which needed to be highly threaded, versus the "rendering" code, which interacted with GameObjects, materials, models, etc--that largely had to occur single threaded, and on the main thread

Thoughts?

brittle mesa
#

Is anyone able to help!
I have an object that is moving down the screen using

    {
        transform.position += new Vector3(0, -2.2f, 0) * Time.deltaTime;
    }```
(I also tried update but its not working)
It looks fine in the unity editor, but when I export it to WebGL the objects are moving much quicker than they are in the editor
Thank you!!!!
vestal arch
#

use the rigidbody

brittle mesa
somber nacelle
#

also that wouldn't result in it moving faster unless you modify the fixed delta time for the webgl build. are you certain that it's moving faster, and not perhaps that the web version has a different resolution / aspect ratio so the camera view is smaller?

hushed widget
#

Good morning - another glorious day of trying to make machines obey me! :>

brittle mesa
#

ive got another problem
I am playing an audioSource using .Play() but when I export it there is a second or so delay until it starts playing, whereas its ok in the unity player

#

does anyone know how to fix that? :)

latent latch
#

There's usually some bool like LoadInBackground for audio clips so look around for that

brittle mesa
#

i think i already selected that but the music is suppose to play right as the scene loads in :(

somber nacelle
brittle mesa
#

yeah its the second scene and music should be playing from the last scene (as there are button presses on that one)

#

even play on awake has the half a second ish delay

latent latch
#

Sounds like it's still probably loading

brittle mesa
#

Is there a way to have a check so I wait until the audio finishes loading and then do the rest of the code?

latent latch
cosmic rain
#

You could have another lighter scene that would load faster and play your sounds/music. Load it first and then the other scenes.

brittle mesa
#

but how does it work if i want to change scene?

latent latch
#

AudioManager.Music2.Play()

rich leaf
#

I have an event-related question.

I want to havea "progress bar" prefab that has its own progress bar script. I want this script to control whenever a float value changes, it updates the progress bar to reflect it.

I want this progress bar to allow other scripts (ie the script for the actual game object that needs the progress bar) to be able to feed in the float value/event into the progress bar script. Essentially,t he progress bar script is generalized to work with any float/float event and its the main scripts job to feed in what float event it wants the progrss bar to be subscribed to

cosmic rain
rich leaf
#

How I can do the above

cosmic rain
#

Implement a SetProgress or something method in the script with the corresponding logic. Get the progress bar script reference and call that method whenever you want to update it.

short quiver
#

My game has WASD movement, and I have a buffer in which I'm saving whether a WASD button was recently released. If that button was repressed in n frames, I'll have the character dash. What's a nice way to map my Vector2 values to the buffer? Here's what I have now, and it works, but it's not easy to read:

public int[] DashBuffer = new int[4]{0,0,0,0};
private Vector2 _inputMoveDirection = new(); 
public Vector2 InputMoveDirection { 
    get => _inputMoveDirection;
    set { // handling dash buffer
        if (_inputMoveDirection.x==-1 && value.x==0) { DashBuffer[0] = _dashBufferDuration;}
        if (_inputMoveDirection.x==+1 && value.x==0) { DashBuffer[1] = _dashBufferDuration;}
        if (_inputMoveDirection.y==-1 && value.y==0) { DashBuffer[2] = _dashBufferDuration;}
        if (_inputMoveDirection.y==+1 && value.y==0) { DashBuffer[3] = _dashBufferDuration;}
        _inputMoveDirection = value;
    }
}
// ...
void FixedUpdate() {
  // ...
  for (int i = 0; i < DashBuffer.Length; i++) { DashBuffer[i]--;}
  // ...
}
violet nymph
#

Could somebody explain rotations to me, I always fail on them, and I have no idea what i'm doing, documentation does not help

leaden ice
#

What would you like explained specifically?

#

"explain rotations" is much too vague.

violet nymph
#

Just how they work mainly, I try using all sorts of things, and they just end up returning values I don't think they should return, such as localrotation/rotation values, should return what's in unity transform view right? It doesn't most of the time, eulerangle does though, it's just confusing

leaden ice
# violet nymph Just how they work mainly, I try using all sorts of things, and they just end up...

Again super vague so I'm not sure what you're looking for.

Unity stores rotations internally as Quaternions. Euler angles are mainly just for convenience and the inspector. Euler angles are not unique. There are infinite ways to express the same rotation with euler angles, so you might not see the same euler angles in the inspector and in code.

It's best to avoid reading Euler angles from a Transform and writing logic based on them for this reason.

violet nymph
#

I see, well let me be more specific: I want to understand how to use .rotation, .localRotation, properly, I currently just apply things by doing Quaternion.Euler, but when I want to calculate something based on the rotation, I don't know how because I don't know the opposite of Quaternion.Euler to convert to a full number (that eulerAngles generates), not sure if that's specific enough, but it's the general idea of what I want explained

#

Euler angles returns the full rotation, like 180,0,0 but rotation returns decimals, and i don't know how to use those decimals

short quiver
#

@violet nymph ^

violet nymph
# short quiver Can you share a specific task you're trying to accomplish? That'll help clarify ...

Well I would prefer learning enough to not need to come back too soon about the same issue, but currently, I am trying to Quaternion.Lerp something with values (for what I need to make now) and modify the values of the original to reach another, but the lerp sometimes goes backwards, doesn't go to its target, goes in circles, so on, so clearly I am doing things wrong here, Changing rotations are easy on there own, but when it gets to the calculations part, it goes all down hill with issues that I can't even comprehend because it just doesn't work, and I see no issue with the code, it just doesn't work for some reason, no matter how much I do, like calculating angles, calculating distances (via eulerangles), etc, it just doesn't work how on the surface of the code, it should

#

Trying to do a very simple thing but still failing, hence why I came here (The past has been the same too, anything with rotations I suck at)

#

I can modify rotations, but all the bugs come along for no reason

quartz folio
#

Please god why have you made 4 threads

short quiver
#

meh

civic isle
#

id like to help but not sure what you mean

raven bobcat
#
    {
        targetScreenPos = cam.WorldToScreenPoint(target.transform.position);
        targetScreenPoint = new Vector2(targetScreenPos.x, targetScreenPos.y);

        proximity = Vector2.Distance(targetScreenPoint, screenCenter);

        if (proximity < (lockAreaImage.rectTransform.rect.width / 2))
        {
            crosshairImage.rectTransform.transform.position = Vector2.Lerp(crosshairImage.rectTransform.transform.position, targetScreenPoint, Time.deltaTime * 25);
            Ray ray = Camera.main.ScreenPointToRay(crosshairImage.rectTransform.transform.position);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity, whatIsEnemy))
            {
                crosshairImage.color = new Color32(24, 180, 0, 255);
            }
        }
        else
        {
            crosshairImage.color = new Color32(53, 53, 53, 152);
            crosshairImage.rectTransform.transform.position = Vector2.Lerp(crosshairImage.rectTransform.transform.position, screenCenter, Time.deltaTime * 10);

        }
    }

lockAreaImage.rectTransform.rect.width/2 don't give me the right radius of the Lock Zone

civic isle
prime lintel
#

Am I retrieving my layers correctly? This is how my objects are setup and what I am receiving in the debugger.

#

Somehow it does not have a layer mask?

untold shoal
#

how can i find a point on a sphere with a given latitude and longitude?

restive dirge
#

Hi guys, has anyone faced the issue of soft input keyboard in android disabling when we select another inputfield, we will have to press again for the softkeyboard to be enabled. The problem persists in only android build, it works fine in IOs. If anyone has a solution pls let me know.

flat marsh
#

Hi, so I was working on my game, in specific the scene transition code (which I'm happy to say I got working all by myself :D), however, one error code kept popping up randomly. Sometimes, it says I will have 2 audio listeners in a scene, even though I know for a fact there is not. The only audio lister is under the "Dont destroy on load" object (I.E its persistant between scenes). To make tripily sure, I even went and looked at even object while I had this error, and guess what? Only 1 audio lister. Has anyone else encountered something similar? If so how did you fix it? Or is it ok to just ignore it as it doesn't seem to be causing issues rn.

flat marsh
leaden ice
#

what do you mean by that

#

Objects don't have layer masks. Objects have a layer.

prime lintel
#

Sorry if I was confusing, as you can see from the picture, the gameobject has a layer of 0x00000000d

leaden ice
#

Yes

#

So what's the issue?

prime lintel
#

May I know what is the right way to compare Layers?

leaden ice
#

0x00000000d is just 13

prime lintel
#

currently I am doing this if (los.collider.gameObject.layer != m_targetLayers.value) continue;

leaden ice
#

that means it's on layer 13

leaden ice
prime lintel
#

I want to know if my gameobject from racasthit belongs to any layer from my m_targetlayers

leaden ice
#
bool IsInMask(int mask, int layer) {
  return ((1 << layer) & mask) != 0;
}```
Basically this^
#

it's a bitmask

leaden ice
#

Why not just use the layermask parameter in the raycast itself

prime lintel
#

i provide it both a collision layer and a player layer, the collision layer dictates walls and obstacles mobs cannot see through

#

I am filtering results by ensuring that rays hit the player before allowing it to see the player

leaden ice
#

you don't need to include the player layer in your mask for that. Just do a linecast

#

using the wall layer

#

and if you don't hit anything, then you can see the player

prime lintel
#

what if it hits another mob collider infront of it?

leaden ice
#

Include any and all obstacle layers in the mask

#

if enemies are obstacles, inlude those

prime lintel
#

ah okay ill try it

#

thank you!

flat marsh
#

Hi, so I was working on my game, in specific the scene transition code (which I'm happy to say I got working all by myself :D), however, one error code kept popping up randomly. Sometimes, it says I will have 2 audio listeners in a scene, even though I know for a fact there is not. The only audio lister is under the "Dont destroy on load" object (I.E its persistant between scenes). To make tripily sure, I even went and looked at even object while I had this error, and guess what? Only 1 audio lister. Has anyone else encountered something similar? If so how did you fix it? Or is it ok to just ignore it as it doesn't seem to be causing issues rn.

#

Here is my code (Give me a second to post):

knotty sun
#

Don't need code.

flat marsh
#

Ok, @ hunabeen said I might so, I was gonna post it just in case

knotty sun
#

Presumably your DDOL has a singleton attached. So when you load the scene until that singleton code is run you will have more than 1 Audio Listener in the scene

flat marsh
knotty sun
flat marsh
#

Oh, XD. Sorry, Monday brain. Didn't realise the abbreviation

merry stream
#

im thinking about refactoring my inventory system and am wanting some input. Right now my inventories are scriptable objects that are changed at run time (i know, sketchy). The advantages of having them as SOs is that it lets me easily drag n drop the inventory anywhere (open it in different UI contexts, etc) as well as have reference to it abitrarily without singletons. Right now it works very well, but it makes it impossible to create new inventories at runtime (chests, loot bags, etc). Any suggestions on how I should go about refactoring away from the SO model while keeping most of the benefits?

flat marsh
knotty sun
flat marsh
knotty sun
#

not really

flat marsh
#

👍 Ok, thanks for all your help :D. Have a nice day

flat marsh
merry stream
#

its exactly like a minecraft inventory, if you know what thats like

leaden ice
flat marsh
merry stream
leaden ice
#

What is your serialization system

merry stream
#

i have a singleton with a list of manually added SO's that will be serialized on close

#

but anyway i dont really like the SO setup so I want to move away from it

merry stream
leaden ice
#

I would say the serialization system sounds like the thing that needs updating/improving then.

But SOs are basically the same as regular classes

#

the difference being that you can create/reference them in the editor

#

but you can also do everything you can do with a regular class with the SO

merry stream
#

hm, so how should I change my serialization system?

leaden ice
#

Change it to include serialization of inventories that were created at runtime as well

#

We're a little light on details here to get into specifics

merry stream
#

how does creating SO's at runtime work? does it persist in the files after the game is closed?

leaden ice
#

no

#

It's just an object that lives in memory

merry stream
#

okay, if you've ever made an inventry system, how did you structure it?

leaden ice
#

Basically an Inventory consisted of a List of Stacks. A Stack is a reference to an Item and a Quantity (Items contain a "maxStackAmount" or something liek that to determine how large the stack can be)

#

Item was an SO

merry stream
#

was your Inventory class a poco?

leaden ice
#

(this was for a game similar to Satisfactory)

leaden ice
#

But, serializable

merry stream
#

yeah, how did you handle things trying to reference them, did you have some singleton InventoryManager or

leaden ice
#

It depends on the specific inventory

#

the main player inventory was more or less referenced by a singleton. Individual structure inventories were referenced in the model for that structure.