#💻┃code-beginner

1 messages · Page 771 of 1

visual heath
#

yes, I'm already storing it, but my logic is broken, and the clients only have display and minimal information about objects, while the server has logic that is stored on the host. Therefore, I need a separated option, and I need to know where everything goes. If you have written what I need, you can send me the documentation. After reading the netcode documentation for gameobject, I haven't found a solution, and I may be blind.

amber pagoda
#

Allow player to choose file directory

visual heath
#

Simply put, I need something like this

public class Client : NetworkBehaviour
{ 

    [Rpc(SendTo.Server)]
    public void SendMessageToServer(string message)
    {
    }

    public void RecieveOnClient(string playerName)
    {
    }
}

public class Server : NetworkBehaviour
{
    private void ReceiveOnServer(string message)
    {
        if (string.IsNullOrEmpty(message)) return;
        string messageToClient = await serverRelease.ReleaseEvent(message);
        SentdToClients(messageToClient);
    }

    [Rpc(SendTo.ClientsAndHost)]
    private void SenddToClients(string response)
    {

    }
}
timber tide
#

There's a multiplayer sample aka BossRoom you can tear apart

graceful dome
#

I have a player gameobject where i'm trying to make it spawn in the center of the generated map (100x100). Whatever i did (from what i know) in my code it ignores to spawn at the center (which should be 50-1-50). It always goes to the location what is written in the player transform 15-1-15. Im lost for now 🥲

timber tide
#

show instantiation code

visual heath
timber tide
#

I mean it is an official unity project by the devs of netcode for gameobjects

graceful dome
# timber tide show instantiation code
    {
        GameObject player = GameObject.FindGameObjectWithTag("Player");
        if (player == null)
        {
            Debug.LogWarning("No Player GameObject found with 'Player' tag!");
            return;
        }

        // Spawn in center - try to find an Air tile
        int centerX = worldWidth / 2;
        int centerZ = worldHeight / 2;

        // First, try to find a walkable spot near center
        for (int radius = 0; radius < 10; radius++)
        {
            for (int x = centerX - radius; x <= centerX + radius; x++)
            {
                for (int z = centerZ - radius; z <= centerZ + radius; z++)
                {
                    if (x >= 0 && x < worldWidth && z >= 0 && z < worldHeight)
                    {
                        if (worldGrid[x, z].IsWalkable())
                        {
                            player.transform.position = new Vector3(x * tileSize, 1f, z * tileSize);
                            Debug.Log($"✅ Player spawned at: ({x}, {z}) - Distance from center: {Vector2.Distance(new Vector2(x, z), new Vector2(centerX, centerZ)):F1} tiles");
                            return;
                        }
                    }
                }
            }
        }```
wintry quarry
#

Also does your player object have a CharacterController component on it?

timber tide
#

If it's an agent too you usually want to use the teleport method it has as it can rubberband you back to previous location

graceful dome
wintry quarry
#

after that, the code of those scripts may be relevant

graceful dome
#

There you go

wintry quarry
graceful dome
#
using UnityEngine;

public class PlayerController3D : MonoBehaviour
{
    [Header("Movement Settings")]
    [SerializeField] private float moveSpeed = 3f;
    [SerializeField] private float rotationSpeed = 10f;
    
    private Rigidbody rb;
    private Vector3 moveDirection;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        
        // Lock rotation so the player doesn't fall
        rb.constraints = RigidbodyConstraints.FreezeRotation;
    }

    void Update()
    {
        // GET Input (WASD / Arrow Keys)
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveZ = Input.GetAxisRaw("Vertical");
        
        // Moving in 3D area (Y stays 0, we move over the ground)
        moveDirection = new Vector3(moveX, 0f, moveZ).normalized;
        
        // Rotate character in direction (optional, later for animations)
        if (moveDirection.magnitude > 0.1f)
        {
            Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        }
    }

    void FixedUpdate()
    {
        // Movement via physics
        Vector3 newVelocity = moveDirection * moveSpeed;
        newVelocity.y = rb.linearVelocity.y; // Keeps gravity/vertical speed
        
        rb.linearVelocity = newVelocity;
    }
}
wintry quarry
#

your log says "spawned at x, z" but the actual code is multiplying by tileSize

#

Debug.Log($"Player position is: {player.transform.position}"); would be a good idea after you move the player too

timber tide
#

I would just remove the for looping atm and just reposition by exact points

graceful dome
graceful dome
wintry quarry
timber tide
#

it's more likely you are changing it but some other system/script is changing it right after on that frame

wintry quarry
#

If it prints the right position after that then either:

  • You have some other code or component moving the player after this code does
  • You're misinterpreting the numbers in the inspector and it has a parent object
timber tide
#

I would even go as far as removing the rigidbody but doesnt seem like the problem

#

but not that I've not done that before ;p

graceful dome
wintry quarry
#

The numbers you see in the inspector are the object's local position. If the object has a parent that is translated, rotated, or scaled away from the origin, the local position will not be numerically equal to the world space position

graceful dome
wintry quarry
#

then it's not that

#

See if adding Physics.SyncTransforms() right after the position setting code helps

#

and/or setting the Rigidbody position instead of Transform

graceful dome
#

now it does spawn at the given log location

wintry quarry
#

setting the Rigidbody position directly instead of the Transform would also do it then

#

it's best to avoid Transform modification for Rigidbodies in general. This is also a bit problematic:

transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);```
#

I'd recommend rb.rotation instead

#

(what you have right now will break interpolation)

graceful dome
#

Alright i'm looking into that.

graceful dome
timber tide
#

Ah so it was the rigidbody. I know that messing with the position could rubberband it, but surprised the rotation is actually tugging at it too

onyx geyser
#

Anyone use Cinemachine here? I'm trying to figure out a way I can make an "enemy" I can drag out, and whenever the player interacts with the enemy, it'll switch to the CombatCam, but I don't wanna attach a new combat cam to every single enemy and would rather just use something that connects each enemy to a specific combat cam

#

would i just use a Cinemachine brain for this?

vale blade
#

Any way to get these tooltips to show up from the summaries?
Feels a bit much to constantly duplicate the text between the tooltips and the docstrings

public class Director : MonoBehaviour
{

    [Tooltip("All gameplay modules in the game. Non-sequential.")]
    [field: SerializeField]
    /// <summary>
    /// List of all gameplay modules in the game. Non-sequential.
    /// </summary>
    public List<GameplayModuleData> _gameplayModules = new();

    /// <summary>
    /// Public readonly getter for all gameplay modules in the game.
    /// </summary>
    public List<GameplayModuleData> GameplayModules => _gameplayModules;

    /// <summary>
    /// The gameplay module that should be loaded upon game start.
    /// </summary>
    [Tooltip("The gameplay module that should be loaded upon game start.")]
    [field: SerializeField]
    public GameplayModuleData StartingModule { get; private set; }
}
oak aspen
#

Is there a way to get the text from the current TextMeshPro page?
Tried finding it in the documentation and on the forums but had no luck with that so far.

naive pawn
oak aspen
# naive pawn what exactly are you trying to get?

I'm trying to get the text that is on the current page
Putting a debug statement with the text value of TextMeshPro only gives me the first two lines, skipping the third one, even if I've changed the page

naive pawn
#

seems like something the folks in #📲┃ui-ux would be able to help with

oak aspen
#

Alright, thank you

hot wadi
#

Tooltips are meant to show inside Unity editor

sand condor
#

Hey I'm trying to do things with Unitys spline package. I see no option to get the t-value of the splines knots. Which means I'd have to loop over the knots, get their position and then use spline.Evaluate to then do things with the result. This feels like a waste of computational power, is the value accessible somewhere? It's not in the BezierKnot struct but I also can't find a function in SplineUtility and the likes.

lavish maple
#

Hi , quick question , maybe not such a short answer, I am new to Unity and game dev in general and am looking to start a pet project myself for a small remake of a much loved old PS2 game.

I have been doing the C# coding myself and have got to the stage where I need to start thinking about a damage system for units - Before I start it I wanted to check if this was perhaps the correct thing to do or should I be looking for and implementing a pre written script at all?

sorry if any of that comes across as if I have no clue what I am doing....As I dont 😄

#

!ask

radiant voidBOT
# lavish maple !ask

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.

-# For more posting guidelines, go to #🌱┃start-here

sand condor
# lavish maple Hi , quick question , maybe not such a short answer, I am new to Unity and game ...

I think the answer to the question depends on what you are trying to achieve. I'd scan the asset store for potential fitting assets, but also check out YouTube as there are some good tutorials that can help you get started.

The asset store probably gives fine solutions, but tweaking them might be a lot of work.
Tutorials can only get you far, depending on your skill level and what your goal is there might be a lot of work to do to get the system to do what you want it to.

Sorry if that is not the most helpful answer, but the question is kind of broad 😅

lavish maple
# sand condor I think the answer to the question depends on what you are trying to achieve. I'...

Thanks for the fast reply!

And don't be sorry was actually the exact guidance I needed for what was indeed a super broad question xD! I suspected I would need to either create it or amend an existing one - really I just wanted to ensure there was not some default script for RTS style damage systems.

In short I just need to create a script to handle:

  • Instances of Damage
  • A damage table to calculate the actual damage a unit takes.
  • Armor/Resistance modifiers
  • Event hooks and callbacks for animations and such.

And I imagine actually much much more , I will have a look to see if anything fits in the asset store and look into amending it to fit , in the meantime Its youtube time I guess!

vital vault
#

how to fix my float var getting like 9th digit inaccurate while calculating? it should only go to first digit after point

wintry quarry
#

What's the context and the end goal?

wintry quarry
vital vault
#

i want to see values like 0.5 on hud, not 0.50

wintry quarry
#

Display it in your HUD with an appropriate number format

vital vault
#

how

#

i use tmp

wintry quarry
#

Check the code example

#

TMP is irrelevant

subtle ore
#

hello i have a problem im creating a 2d game and i added a weapon system that shoots projetiles but the projetiles are not showing if im playing i added sprit render and all the stuff but its not working

can someone help pls

onyx lark
hot wadi
onyx lark
#

Code would maybe be useful too. I'm guessing it might have something to do with incorrect projectile rotation

subtle ore
#

using UnityEngine;
using System.Collections.Generic;

public class ProjectileController : MonoBehaviour
{
// Settings
private int damage;
private float speed;
private Vector3 direction;
private float lifetime;
private bool piercing;
private int maxPierceCount;
private GameObject hitEffectPrefab;

// State
private float lifeTimer;
private int currentPierceCount;
private HashSet<GameObject> hitTargets = new HashSet<GameObject>();

public void Initialize(
    int dmg,
    float spd,
    Vector3 dir,
    float life,
    bool pierce,
    int maxPierce,
    GameObject hitEffect
)
{
    damage = dmg;
    speed = spd;
    direction = dir.normalized;
    lifetime = life;
    piercing = pierce;
    maxPierceCount = maxPierce;
    hitEffectPrefab = hitEffect;

    lifeTimer = lifetime;
    currentPierceCount = 0;
}

private void Update()
{
    // Movement
    transform.position += direction * speed * Time.deltaTime;

    // Rotation
    transform.rotation = Quaternion.LookRotation(direction);

    // Lifetime
    lifeTimer -= Time.deltaTime;
    if (lifeTimer <= 0)
    {
        Destroy(gameObject);
    }
}

private void OnTriggerEnter(Collider other)
{
    // Ignore player
    if (other.CompareTag("Player")) return;

    // Ignore already hit targets
    if (hitTargets.Contains(other.gameObject)) return;

    // Hit enemy
    if (other.CompareTag("Enemy"))
    {
        hitTargets.Add(other.gameObject);
        ProcessHit(other.gameObject, other.transform.position);

        // Check piercing
        if (piercing && currentPierceCount < maxPierceCount)
        {
            currentPierceCount++;
            Debug.Log($"[PROJECTILE] Pierced! ({currentPierceCount}/{maxPierceCount})");
            return; // Don't destroy
        }

        // Destroy projectile
        SpawnHitEffect(other.transform.position);
        Destroy(gameObject);
    }
    // Hit wall
    else if (other.CompareTag("Wall") || other.CompareTag("Obstacle"))
    {
        SpawnHitEffect(transform.position);
        Destroy(gameObject);
    }
}

private void ProcessHit(GameObject target, Vector3 hitPoint)
{
    // Apply damage
    Enemy enemy = target.GetComponent<Enemy>();
    if (enemy != null)
    {
        enemy.TakeDamage(damage);
        Debug.Log($"[PROJECTILE] Hit {target.name} for {damage} damage");
    }
}

private void SpawnHitEffect(Vector3 position)
{
    if (hitEffectPrefab != null)
    {
        GameObject effect = Instantiate(hitEffectPrefab, position, Quaternion.identity);
        Destroy(effect, 2f);
    }
}

}

#

this my projetile controller

hot wadi
#

!code

radiant voidBOT
subtle ore
onyx lark
#

If it's a 2d rotation, I'd set euler angles with atan math

hot wadi
#

This code is only controlling the projecting, not instantiating it

#

Where are u instantiating it?

subtle ore
onyx lark
#

I'm currently not on pc. But it seems you only need z rotation, x and y will make your projectiles rotate in a way where you will often not see them.

#

I might be wrong tho as I don't use quaternions often and they often caused issues for me in 2d

subtle ore
#

hmmm.. oke you know a better way ?

naive pawn
#

(not an issue, just something you could utilize to make it more concise)

#

instead of a field and a method:

private float x;

public float GetX() => x; // shorthand for `{ return x; }`
```you could use a property:
```cs
public float x { get; private set; }
onyx lark
#

You take direction x and y and set your object's euler angles to new Vector3(0,0,Mathf.Atan2(y, x)* Mathf.Rad2Deg);
Also you don't need it on update, only rotate once on spawn

wintry quarry
#

You can just do transform.right = direction;

#

(for the object you want to rotate)

onyx lark
#

Oh fg

wintry quarry
#

No need to do all the trig yourself

onyx lark
#

Well it's more fun with manual labor but I didn't realize I could do this too

onyx lark
subtle ore
#

im tying it rn

onyx lark
subtle ore
#

can i send pic off my scene ?

naive pawn
#

sure

subtle ore
rich adder
#

why is X your "forward" 🤔 aren't you doing 2d

naive pawn
#

that is definitely pointing in the wrong direction

#

(if you can't tell what's wrong, try changing to the 3d scene camera at the top of the scene window)

subtle ore
#

ohhhh crap

#

i think i found the problem

#

thx how can i fix this

onyx lark
#

What's the current rotation code?

#

Just paste the part here with
```
```

naive pawn
#

wrong quotes

onyx lark
#

Fixed it!

naive pawn
#

(also add cs)

onyx lark
#

Am on phone. All quotes are the same

naive pawn
#

they most definitely are not

onyx lark
#

Mostly

naive pawn
#

...yeah, no

onyx lark
#

Initially they seemed to look the same 🥲

naive pawn
#

a language for the codeblock would also be appreciated
```cs
// your code here, on a separate line from the fences
```

naive pawn
subtle ore
#

is this right float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
proj.transform.rotation = Quaternion.Euler(0, 0, angle);

naive pawn
#

doesn't seem wrong, is this the code you were previously using?

#

(make sure to save first)

naive pawn
subtle ore
#

no its new code

naive pawn
#

perhaps try it before asking 😉

rich adder
#

you can just do what Praetor suggest and do transform.right = myDir

#

but you gotta fix your orientation properly

molten cipher
#

kinda hard to explain
but basically i have a Ground Check for a rigidbody

isGrounded = Physics.CheckBox(groundCheck.position, checkBoxScale, boxOrientation, groundLayer);

i also use a RigidBody based character controller.. and i have root motion animations.
when i perform the "Roll" animation.. when just before it ends the animation the "isGrounded" CheckBox is getting collided with the ground mesh.. and for a 0.1 second it feels bad.. like a glitching.. or hitting the Air.. i'll try to send Gizmos as well...

the locomotion animation logic with groundcheck

        //-- locomotion animator
        if (isGrounded)
        {
            float targetSpeed01 = moveInput.magnitude; // from 0 to 1
            animator.SetFloat("BlendSpeed", targetSpeed01, 0.1f, Time.deltaTime);
            animator.speed = moveSpeed;
            animator.SetBool("Falling", false);
        }
        else // play animation for the Falling and stop the movement. 
        {
            rb.linearVelocity += Vector3.up * Physics.gravity.y * (fallMultiplier - 1f) * Time.deltaTime;
            animator.SetFloat("BlendSpeed", 0, 0.1f, Time.deltaTime);
            // animator.SetBool("Falling", true);
            StartCoroutine(DelaytheFall(fallDelay));
        }

        // --- JUMP ---

        if (jumpPressed && isGrounded)
        {
            animator.SetTrigger("Jump");
        }

the one more interesting fact is that the Glitching effect stops if i play at 4k resolution... idk if this info is usefull...

can you help?

rich adder
#

it just looks like the animation making go under the ground then the physics snaps it back up ?

#

or actually other way around

#

it floats for a bit then gets pushed down when gravity activates / rigidbody

molten cipher
#

yeah but i have constant gravity applied at the rigid body also when i jump off a block it still is making that animation linearly.. so root motion isn't applying gravity it seems...

rich adder
#

why would it? root motion overrides the transform

molten cipher
#

i'll try to disable root motion as long as jumping is active

rich adder
#

personally i just time it through code instead of relying on root motion when i got physics

molten cipher
#

yeah i thought about it but i wanted to add custom animations for it later... but i think i should , as you said, time it trough code later and keep the simple animation.. yeah probably will be less of a brainrot.

rich adder
peak helm
#

could I get some help with my code? I'm pretty new and as the code is written right now, it obviously changes the colour very fast at high framerates and very slowly at low framerates. Could I get a pointer as to how I could make it tied to a certain amount of time? Like, if I want B to go from 0 to 255 in 4 seconds, how could I do that?

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

public class Hunter : MonoBehaviour
{

    public SpriteRenderer rend;
    //for changing the renderer in unity

    public float R, G, B;
    public Color currentColor;
    //for colors

    void Update()
    {
        if (Human.blueDead == true && B < 255)
        {
            B++;
        }
        
        if (Human.greenDead == true && G < 255)
        {
            G++;
        }
        
        if (Human.redDead == true && R < 255)
        {
            R++;
        }

        currentColor = new Color(R/255, G/255, B/255);;
        rend.color = currentColor;
    }
}
peak helm
#

i figured, but I don't really know how to add it

rich adder
#

also you can use a for loop for this too

#

maybe even a coroutine

peak helm
#

i forgot about for loops but i dont know what a coroutine is

naive pawn
#

you could use a scale from 0 to 1 instead of counting up to 255

#

that way you can use fractions

#

basically you'd specify how much time it should take overall, and then you'd keep track of how much time has passed

peak helm
#

yeah this was the fastest and easiest way I thought of, just to make sure it works first. But then i realized I have no clue how to actually do it properly

naive pawn
#

dividing the latter by the former, you'd get a value from 0 to 1

peak helm
#

that's exactly what I'm looking for

rich adder
naive pawn
#

right now the ++ is basically what's counting up, 1 each frame
but you'd want it to count up some amount each second instead
that's what deltaTime is, a conversion factor - it's seconds per frame

peak helm
#

thanks

#

I'm not sure I fully understand yet but I'll try reading the coroutines page and test some stuff out. I'll return if I get stuck again. Thanks y'all <3

rich adder
#

Update will be fine too

peak helm
#

yeah I know but it seems like a tool that would be useful to learn for the future

rich adder
#

oh fo sho

molten cipher
#

Update:
Fixed it trough adding the Delay for Actual jump.. and baked the Y position for the Root Motion...

    [SerializeField] float jumpForce = 5f;
    [SerializeField] float jumpDelay = 5f;
        if (jumpPressed && isGrounded)
        {
            StartCoroutine(HandleJump(jumpDelay));
            animator.SetTrigger("Jump");
        }
    IEnumerator HandleJump(float delay)
    {
        yield return new WaitForSeconds(delay);
        rb.AddForce(Vector3.up * jumpForce * Time.fixedDeltaTime, ForceMode.Impulse);
    }
#

thanks for your help nav

rich adder
molten cipher
#

🫡

rich adder
#

AddForce already moves it on fixed physics tick*

slender nymph
#

if you're trying to sync up the actual force with an animation use an animation event rather than a specific delay so that you can sub in any animation with the event and have it correctly synced rather than needing to adjust the timing manually.

also yeah, don't use deltaTime with forces. you'll likely need to reduce the jumpForce in the inspector after removing that extra multiplication

rich adder
#

^true animation event will be much easier

#

(just make sure transitions don't skip it)

slender nymph
#

oh and if you want consistent jump height it's usually best to also reset the vertical velocity to 0 right before adding the force

tight fossil
#
 string chatName = allDataInMessage[4].Substring(1, splitPoint - 1);```

How do I change this so chatName equals the 2nd half of the message rather than the first
naive pawn
#

Substring(splitPoint + 1)

slender nymph
#

i feel like there's definitely a better way to do whatever you are doing here though

naive pawn
#

but splitting would probably be easier to work with

#

is the first character always a = here? (somewhat unrelated)

tight fossil
#

no actually "=" is in the middle of the two strings, this is older code im trying to change up to adhere to the array ive now set up

naive pawn
#

also, is the end not exclusive?

naive pawn
tight fossil
slender nymph
# naive pawn but splitting would probably be easier to work with

would splitting a string rather than just working with a custom type that has the info already separated into relevant properties be easier though? because from what little they've shown, it seems like this is probably stuff sent over the network for a chat message and they can, and probably should, just use a custom type instead of packing it all into a single string and manually splitting it

tight fossil
naive pawn
tight fossil
#

but your solution worked so thanks :)

rich adder
#

struct {
string author
string message

naive pawn
tight fossil
slender nymph
#

i mean, actually defining a type that you put your data into so that it isn't all in a single string

naive pawn
#

that's not what i was referring to either

hot wadi
#

Don't iterate a string if not neccessary

rich adder
#

hell you can even put date, modified time whatever other types in it

tight fossil
#

i dont understand what your message means, the whole message arrives in a single string, how do i split it without splitting it?

slender nymph
#

you put it into your custom type at the sender, not at the receiver

rich adder
#

Its not gonna be a single string... it will be its own type

slender nymph
#

then just deserialize it at the receiver back into that type

rich adder
#

like ChatMessage chatMessage = new()
chatMessage.author = "username "
chatMessage.message = "whatever"

#

if you want it to be compatible with not just c# you can probably just make it into json easily

#

single string then splitting shit is absolute nightmare

#

if your message has symbols you defined as split string symbols you're gonna have a bad time and account for that

slender nymph
#
public struct ChatMessage 
{
    public string Name { get; private set; }
    public string Message { get; private set; }
    public DateTime Time { get; private set; }
    //etc
    
    public ChatMessage(string name, string message, DateTime time, etc)
    { //assign to properties }
}

void SendMessage(string message)
{
    var chatMessage = new ChatMessage(name, message, DateTime.Now, etc);
    
    //logic to actually serialize then send the message over the network
}

void ReceiveMessage(ChatMessage chatMessage)
{
    //this is the end point that has already deserialized the data back into a ChatMessage
    Debug.Log($"[{chatMessage.Time}] {chatMessage.Name}: {chatMessage.Message});    
}
#

basically that, but obviously not the stripped down version that this is

tight fossil
#

and how do i grab the giant string of data coming in and parse it into these variables if not with a .Split?

rich adder
slender nymph
#

you don't because you don't use a giant string of data in the first place. you use this ChatMessage struct and serialize that, then send the serialized data over the network, then at the receiver you deserialize it back into a ChatMessage. at no point do you construct a giant string of data that will need to be manually split

naive pawn
#

-# well, clearly not json with ; and =

rich adder
#

yeah so they're probably writing the data in the first place, so don't write it as giant string lol

#

I meant if its needs to be a long string, json at least is formatted

tight fossil
#

im getitng the data from StreamReader using the twitch client GetStream

#

reading chat messages sent on Twitch

rich adder
#

I only worked with discord, but pretty sure twitch also has some type of sdk or api you can get the message properly formatted

slender nymph
#

presumably it's sending json from its api so you would just create a type you can deserialize that json into

molten cipher
rich adder
tight fossil
#

i think im good guys, this is just a personal project anyways

slender nymph
#

just looked up the api, and yes. its endpoints all return json that just needs to be deserialized so all of this manual parsing of the messages is pointless and just serves to waste time and performance

tight fossil
#

im just a beginner man why you gotta be so mean

slender nymph
#

at no point was i being "mean" here, i am simply pointing out facts. it takes just a few minutes to look up how to deserialize json, and unity even has some built in tools that should be able to handle this easily

rich adder
#

splitting strings can be also very error prone

tight fossil
#

sure thing guys, ill talk to a coder friend of mine when theyre free about how to deserialize the message

rich adder
#

though with stuff like Newtonsoft you don't need ALL the fields

tight fossil
#

but calling someone's honest effort a pointless waste of time and performance is mean, even if you don't think so or even meant it

slender nymph
#

if you cannot take constructive criticism, then perhaps don't ask for help online 🤷‍♂️

#

but manually parsing these strings does take more time than simply learning how to deserialize the data properly. it's also going to take more performance to do so because of the number of times you are querying these strings

#

how did you even get these strings into this format in the first place? because with the data being sent as json there shouldn't even be any = or ; to split on unless those are in the actual chat message (which means your split is breaking, hence the extra time to figure out how you can avoid wrongly splitting the string)

tight fossil
#

what do you mean by json, im getting this data as a string through the code.

reader = new StreamReader(twitchClient.GetStream()); + string message = reader.ReadLine();

is giving me the message as a string

rich adder
tight fossil
#

with twitchClient = new TcpClient("irc.chat.twitch.tv", 6667); using other strings to get the twitch stream in question

#

        writer.WriteLine("PASS " + password);
        writer.WriteLine("NICK " + username);
        writer.WriteLine("USER " + username + " 8 * :" + username);
        writer.WriteLine("JOIN #" + channelName);
        writer.WriteLine("CAP REQ :twitch.tv/tags");```
rich adder
#

is there a reason to use TCP client instead of the API ?

tight fossil
#

every tutorial online ive seen does this okay, don't ask me

slender nymph
#

so you're not using the api of a very similar name then. you need to actually provide this info up front, you can't just expect us to intuit that you are doing things like this

tight fossil
#

i only asked how to split a string the other way around man...

#

you kept prying about it 😭

rich adder
#

people often want to know more so they can give you the best solution to a problem, no reason to get defensive

slender nymph
#

because what you are attempting to do is incredibly fragile and will break

#

whoops someone's message contains a character you're splitting the string on, now your entire setup is broken!

naive pawn
#

the X here being getting info over a network
the Y here being the condensed info string with manual parsing, when the better option would be proper serialization and deserialization (what nav/boxfriend are trying to explain)

tight fossil
#

you know what, fuck it, i cant change how you think.

anyways, thanks Chris ill check it out 👍

dull pine
#

Hi! I need some help. Who can help me with my project? I have some problem with my navmesg in procedural maze

rich adder
dull pine
#

Can i talk with you in voice chat pls?

#

ohhh (

dull pine
rich adder
#

your navmesh agent is not near it / its not valid for it

#

without showing the setup you got goin its hard to offer any other suggestion

dull pine
#

But i think its code becouse we have procedural gen maze. In screenshot you can see room who build maze

#

I can send code if it can help

#

Its all codes for generation

rich adder
dull pine
#

I dont understend how it work( enemy cant go to another blue place bcs have chasm

#

I dont know how to fix it

rich adder
cosmic quail
dull pine
#

all ... i dont khow how it work in unity bs i work in un4

slender nymph
#

this is a code channel

radiant voidBOT
molten cipher
thorn holly
#

I’m adding an enemy to my game that i want to move using transform.translate since I don’t need it to have physics collusions. However, it does have a trigger collider attached to it so it can hit the player and deal damage. If I move it directly with transform translate, is this incompatible with the hitbox detection?

#

moved this from unity talk cause accidentally posted in wrong channel

rich adder
nocturne kayak
#

hello guys i'd like to know how to make a good raycast that will shoot from the middle of the screen i have tried to shoot from the camera but its not really accurate :) In case you need it, here's my script. RaycastHit hit; Debug.DrawRay(transform.position, CameraDirection.transform.forward * 10, Color.red); if (Physics.Raycast(transform.position, CameraDirection.transform.forward, out hit,10))

thorn holly
rich adder
#

translate can work with triggers but it has to "catch up" and can yield inaccurate results
you still need a rigidbody between the two

thorn holly
#

should they both have a rigidbody?

rich adder
slender nymph
rich adder
thorn holly
thorn holly
#

so wait should i:

  1. not give the enemy a rigidbody and move it with transform translate
  2. give the enemy a kinematic rigidbody and move it with transform translate
  3. give the enemy a dynamic rigidbody and move it by setting velocity
thorn holly
nocturne kayak
rich adder
slender nymph
thorn holly
#

so i should do the first one for simplicity?

rich adder
#

depends what you need to do, generally a rigidbody per enemy can be taxing depending how many enemies you will have

nocturne kayak
#

uhm , i have attached the camera to the player , but the camera still move right ? i dont know if this is the good thing to do tho 😆

#

oh no i'v done transform.position

#

i think i might be dumb

rich adder
#

if you want enemies to get hit with a trigger and do damage, then you need the trigger that hurts them at very least to have a rigidbody

thorn holly
#

so ill give the enemy a kinematic rigidbody

thorn holly
nocturne kayak
rich adder
thorn holly
#

does this create problems since the player already has a dynamic, is not trigger rigidbody for collisions with the ground?

rich adder
#

player hits a trigger to hurt it , you dont need a rigidbody on the hurtzone

#

if player has rb

thorn holly
#

yes but the player has 2 diff colliders

#

one is a dynamic not trigger rigidbody and collider for where it can collide with the ground

rich adder
#

iirc the rigidbody counts child colliders are part of rb but I could be wrong

wintry quarry
queen adder
#

ive got a script that activates another gameobject after some time, how can make it so that the gameobject does something upon activating from code attached to it(the gameobject)?

slender nymph
#

put a component on it that has the OnEnable method

wintry quarry
#
myObject.SetActive(true);
myObject.GetComponent<MyScript>().DoSomething();```
#

another option is - as box said, use OnEnable

queen adder
#

i think onEnable would be good

#

ty

warm sequoia
#

Hi, so im a bit stuck, my PointerEventData does never run for some reason, everything should be setup right so I dont really know what to do

wintry quarry
#

PointerEventData is a class. Classes don't "run"

warm sequoia
#

It means that this method wont run:

wintry quarry
#

Ok you mean OnDrag won't run then

warm sequoia
#

yeahh

wintry quarry
#

You need to show how you set up the scene

#

And the rest of the script

#

!code

radiant voidBOT
warm sequoia
wintry quarry
#

The name is required to implement the interface you should be implementing

#

You need to show the full script

warm sequoia
wintry quarry
#

(and preferably while or after you drag)?

Also show the inspector for the InnerImage object

warm sequoia
wintry quarry
#

Have you saved your code?

#

You have IPointerDownHandler but there's no OnPointerDown method implemented, that should be a compile error

warm sequoia
#

Yeah it doesnt exist

wintry quarry
#

What doesn't exist

warm sequoia
#

THe IPointerDownHandler

#

in the class

#

I forgot to remove it

wintry quarry
#

Sounds like you haven't saved your code

warm sequoia
#

I have 🙏

wintry quarry
#

Ok so can you show theinspector of that object?

#

InnerImage

warm sequoia
wintry quarry
#

Why does it have a BoxCollider

warm sequoia
wintry quarry
#

UI should not have colliders

warm sequoia
#

and he said I needed it

wintry quarry
#

remove the collider

warm sequoia
#

for some reason

wintry quarry
#

Because you confused it with world space physics objects

#

you don't need that for UI

#

You also have an Event Trigger component that may be interfering

warm sequoia
#

both are removed now

wintry quarry
#

Can you show your canvas inspector too

warm sequoia
#

yeah

warm sequoia
#

BackgroundImage:

wintry quarry
#

hmm i do wonder if the mask is doing something here 🤔

#

If you put IPointerEnterHandler/IPointerDown on the script does that work?

warm sequoia
#

Yeah im wonder where the logic is in this stuff

sour fulcrum
#

thats a very small image

wintry quarry
#

Also yeah can you actually see this image?

warm sequoia
#

image?

#

which image

wintry quarry
#

Wdym which image

#

the thing you're trying to drag

#

InnerImage

warm sequoia
#

this image?

wintry quarry
#

Idk

#

what is that

sour fulcrum
#

.. in the scene

#

thats the asset preview

warm sequoia
wintry quarry
#

In game view when you're actually playing the game

warm sequoia
#

💀

wintry quarry
#

Also is this a first person game?

warm sequoia
#

when I click space yes it comes up

warm sequoia
wintry quarry
#

So it's a first person game?

#

Ok that's possibly the issue

warm sequoia
wintry quarry
#

Pointer events with a locked/hidden cursor don't usually work

#

are you unlocking/showing the cursor when bringing up the map?

warm sequoia
#

I mean its still hidden so I dont think so

#

but I dont want it to be shown either

wintry quarry
#

Yeah that'll be why. Search for "Unity eventsystem IPointer locked cursor"

wintry quarry
#

mouse dragging doesn't make much sense to me with a hidden cursor

wintry quarry
#

I would just read the mouse delta input directly and move the map based on it.

#

this isn't pointer dragging behavior, since there's no pointer

warm sequoia
#

innerimage

wintry quarry
#

whatever you want to move

#

yes

warm sequoia
wintry quarry
#

sure

#

honestly don't feel like I would use canvas/UI for this at all. I'd probably use a quad with a material and change the texture offset

#

but same difference

warm sequoia
#

Is that easier

#

becouse if it is, I want to do it

#

becouse im stuck

wintry quarry
#

it's easier for me.

Try this:
make a new material.
Add your map image as the albedo image on the material
Add a basic quad to the scene
Put the material on it, you should see the map on the quad.
Then modify the offset in the material inspector

#

and see what happens

#

you should get the basic effect you want

#

it will require a little tweaking after that for scaling and stuff but should get you most of the way there

warm sequoia
wintry quarry
#

Materials don't go in the scene

#

they are just assets

warm sequoia
#

ooh

rich adder
warm sequoia
#

im dumb but where do you find albedo image in here?

rich adder
#

Base Map

warm sequoia
#

which section?

rich adder
#

Albeido is the name for Standard materials

rich adder
#

texture goes in here

warm sequoia
#

but I can only change color... image? png?

#

oooh

#

ohhh

rich adder
#

if you don't want the quad / map be affected by lighting you can also make it Unlit instead of Lit

warm sequoia
#

NOOOO unity I hate you, why do you remove all my stuff when I pause the game after having it on 😭 😭 😭 😭

wintry quarry
#

To be honest you'll probably want a (simple) custom shader for this to insert white pixels at the edges or something, but if you set the wrap mode on the imported image to "Clamp" you'll get a decent result to start with

rich adder
#

not sure why its not default

warm sequoia
#

my quad doesnt want me to drag the material to it

#

it just shows this symbol: 🚫

rich adder
polar acorn
warm sequoia
#

nvm

#

but should it be the mesh render?

wintry quarry
polar acorn
#

A renderer has a material.
The material has a texture.
The texture is your image file.

warm sequoia
wintry quarry
#

there's a place to put the material inside there

#

replace the default one with your custom mat

warm sequoia
#

yoo this is cool stuff

rich adder
#

you probably wont need a mesh collider for this

rich adder
warm sequoia
#

cool

#

But as I want right now do I want one white image and then a inner image, how should I do that now?

warm sequoia
rich adder
#

clone it maybe ?
or you could make the mesh have 2 materials but you probably would need to figure this one in blender

warm sequoia
#

blender?

#

why would I need blender

warm sequoia
rich adder
#

could work, but remember you don't need mesh collider otherwise other objects that move like an enemy might bump into it

#

or even your char

warm sequoia
#

btw, I cant really hardcode the map image, because the player will upload it

rich adder
#

thats fine you can assign textures to materials at runtime

#

do keep in mind that this is a world object so if you run into an obstacle and your player collider not big enough it will phase into object

#

for that you can set this layer into its own thing then use a Renderer Feature that allows you to make this object appear over everything else so if you bump into a wall you don't have the map phase through it

warm sequoia
#

I think

warm sequoia
#

but I still dont really understand how to do the backgrund image thing

rich adder
warm sequoia
#

but why would I need to objects (two quads)?

wintry quarry
#

it would be a very simple custom shader

#

but for now I would just recommend setting your image to Clamp

sour fulcrum
#

theres many ways of doing that

warm sequoia
#

Im counfused should I make a shader or two quads or both?

wintry quarry
#

one or the other

#

but the shader will be a simpler setup overall

#

and two quads would require a masking technique

warm sequoia
wintry quarry
#

Did you see what happens?

warm sequoia
#

yeah it dissperad

#

or wait

#

if the value is less then 1

#

it moves

#

But I want to be able to rotate the image

#

also zoom in / out

#

not just offset

#

is that what the shader is for?

rich adder
#

yes

#

use the shader graph you can make those into variables you can mess with

wintry quarry
#

you can probably look up a simple rotatable/offsettable shader

warm sequoia
#

okey, I will do that tomorrow, but how do I detect mouse interactions in this cause?

rich adder
#

its 1 node with ShaderGraph

wintry quarry
#

but that's an input handling question

warm sequoia
#

this one I think

wintry quarry
#

since you're using the new input system you'd make an input action for the mouse input

#

and then read it

warm sequoia
#

I google how to do that tomrrow ig

rich adder
#
[SerializeField] private InputActionReference mouseAction; // default actionmap should already be there for mouse if input system is installed, drag the action "Look" here in inspector
Vector2 mouseInput;
void Update(){
mouseInput = mouseAction.action.ReadValue<Vector2>();
wintry quarry
warm sequoia
#

I guess this maybe

wintry quarry
#

but - if you're using both, then yes

#

you can do that

#

Seems like your project is probably using both

warm sequoia
#

old youtube tutorial lmao

warm sequoia
#

Thanks for the help god night

rich adder
radiant voidBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

warm sequoia
#

I have the student package from jetbrains (which contains rider I think) because I’m using intellij for my Minecraft plugins

rich adder
#

idk if student license allows commercial projects, look into it (if you plan on making money from this game)

solar hill
#

but also whats stopping you from just switching to a different editor pre release 🤔

lavish maple
#

I’m trying to use additive async multi scene loading using the built in save /load scene system but running into some issues .

Firstly , the scene transition worked fine when just using standard save / load new scenes but since trying to make it additive I run into alot of errors .

I just wanted to check it there were any key “ rules “ around using Save and Load scene in this way .

I believe my issues stem from duplicated cameras and event scripts but not 100% . Just wanted to see if there were any known Do’s and Dont’s - thanks for any help in advance !

solar hill
#

pretty sure you have to make sure that each additive scene only has one active event/camera controller

#

i think

lavish maple
solar hill
#

but im not too familliar with the workflow so i would stick around for someone else to give a better answer lol

lavish maple
#

Ha no problem thanks anyway though . I’m brand new to unity so it all helps !

slow blaze
#

Hey guys I wanted to ask
How would I go about connecting things (like a node system) in unity?
I would connect the ins and outs of gates like this to do some operation based on t he connected data

wintry quarry
solar hill
wintry quarry
#

like - are you trying to make a boolean logic gate game, is that the question?

slow blaze
wintry quarry
#

I wouldn't use UI, for one

slow blaze
wintry quarry
#

So I guess my question is what part of this are you struggling with?

#

The visuals?

#

The logic?

#

the data structures?

solar hill
#

youre basically inventing a low level symbolic programming language

#

in a way

slow blaze
solar hill
#

im guessing approach and implementation of said systems

#

from a technical standpoint

wintry quarry
slow blaze
#

Like I have the code and function ready, I just dont know how to use it when unity comes to play
to show these things in game

wintry quarry
#

or just have them there automatically

#

and have the player place or connect other nodes

#

I could see this being done by allowing the player to:

  • Place nodes
  • connect existing nodes
  • change the type of existing nodes

or all of the above

#

but that's a gameplay design decision

slow blaze
#

yes thats what I had in mind
I'm struggling with (connect existing nodes)
I'm confused by how to make that happen and how to get data from node connections

wintry quarry
slow blaze
#

that is true

wintry quarry
#

when you make the connection, you add your node to the input node slot for the node you're feeding into

#

like a simple example:

class OrNode : AbstractNode {
  AbstractNode[] inputNodes = new[2];

  public void SetInput(int index, AbstractNode node) {
    inputNodes[i] = node;
  }

  public override bool Evaluate() {
    return inputNodes.Any(node => node.Evaluate());
  }
}```
vital vault
#

how to serialize/deserealize list of objects?

#

like this

#
{
  "objectData": [
    {
      "id":1,
      "name":"object 1"
    },
    {
      "id":2,
      "name":"object 2"
    }
  ]
}
rich adder
vital vault
#

what do i write in my root obj

rich adder
vital vault
#

i know that

#

this is object code

#

now smth like

[System.Serializable]
public class Savefile{
    public List<MyObject> objectData;
}``` i guess?
rich adder
vital vault
#

also i want to make my project as independent as possible

rich adder
vital vault
vital vault
#

because im used to it and well...

#

i already have a project to copypaste savefile manager from

rich adder
#

jsonutility is fine just annoying to work with especially with properties, dictionaries you have to always make wrappers

vital vault
#

2 jsons in one file

#

like it has 2 root entries

rich adder
vital vault
vital vault
vital vault
#
{
  "somecrap":"fdihdffd"
}
{
  "someothercrap":"bruh what"
}
rich adder
vital vault
#

i remembered a joke

#

a monkey is calling the devs of a lib instead of reading the docs

#

dont be dumb as monkey

#

continuation: monkey is actually smart because nobody wrote the docs

rich adder
#

ouch lol

#

dev who puts a tool without docs, is not tool I'd wanna use anyway UnityChanLOL

vital vault
#

but there are some tools that dont need a doc

rich adder
#

“Why do you keep calling us?”
And the monkey just shrugs:
“Why do you keep shipping undocumented features?”

vital vault
#

like this piece of code (one of the worst type of protection for savefile in the game):

static public string ProcessSavefile(string input)
{
    string output = "";
    for (int i = 0; i < input.Length; i++) {
      output = output + (char)(input[i] ^ key);
    }
    return output;
}
#

yea its basic XOR key prot

rich adder
#

ohh protection ?

vital vault
#

kinda

rich adder
#

I just create a hashing system xD

vital vault
#

but its really dumb to encrypt json savefile with xor

rich adder
#

if it don't match the hash, sorry you fucked up your savefile.. I dont accept it

vital vault
#

scince any json must begin with {

vital vault
rich adder
#

from tampering no, but you can verify that it was fucked with through hashing

vital vault
#

also without obfuscation il2cpp dumper + dnspy + ida goes skidddd

rich adder
#

i create a secret copy of the original save file, if you mess with the one from the common user folder. I just restore it from the "secret copy"

rich adder
#

in most cases they can find where you save that too though

#

so if you brick your save, sucks for you

vital vault
#

lets be real: you can just use handle list

vital vault
rich adder
#

hm interesting.. I never checked their code

vital vault
rich adder
#

ofc you can always make your game "always online" and use servers, thats pretty much tamper proof

vital vault
vital vault
#

there is no unhackable system

#

but some systems are taking longer to hack

#

its a game of cat and mouse

rich adder
#

yes thats the point, you have to make it as tedious as possible.. indeed nothing is truly hacker proof. thats why these AAA studios spent tons of money on

sour fulcrum
#

Why try and safeguard the save file in the first place

rich adder
#

remember Fallout 76 and all that bullshit with the Devrooms

grand snow
#

checking the hash of a local save wow 😆

rich adder
thorn holly
#

If its a single player game honestly dont bother making it tamper proof

#

People will appreciate the extra freedom ngl

grand snow
rich adder
#

hard lessons learned Im sure

grand snow
#

Yea people will either find a way to do it properly, mod the game or just hate you

sour fulcrum
#

i would hope it was their fault would be abit worrying otherwise 😅

rich adder
#

it can mess with the pacing of your game though in some cases

vital vault
rich adder
#

clickteam fusion holy shit

grand snow
vital vault
#

thats what i meant

grand snow
#

i know!

vital vault
#

like if you write your game from scratch in C++ and asm and then vmprotect it, it will be more practical to drop it

sour fulcrum
#

Almost impossible is coward talk people are starting to decomp gamecube and wii games 😛

#

there will always be psychos

vital vault
#

how can i transfer from jsonutility to json.net

rich adder
#

get the package lol

#

use JsonConvert.SerializeObject instead of JsonUtility.ToJson

#

etc

vital vault
#

how do i convert my types

#

[Serializable] classes

rich adder
#

wdym convert?

vital vault
rich adder
#

yes

#

only changes which methods you use, you can keep everything else the same. As mentioned you also wont need most wrapper bs you need for JsonUtility

vital vault
#

ok

rich adder
#

the only thing you need to be careful with is Vector2/3 struct as it causes weird error

#

cause it creates a Self-referencing loop error

#

easy fix tho

grand snow
#

You can use float3 from unity mathmatics as an alternative

rich adder
#

or make your own struct too

grand snow
#

they have implicit conversions to Vector types

rich adder
#

but yeah that also works

vital vault
#

im kinda new to serializing, how to represent this:

{
    "playerData":{
        "x":21,
        "y":56,
        "z":53,
        "ry":82,
        "rx":24
    }
}
grand snow
#

make class

rich adder
vital vault
#

how can i make an object in json that can be dynamic?

#

i need to save object data, but diffirent types of objects have diffirent properties

rich adder
#

like polymorphism ?

vital vault
#

yea kinda

rich adder
#

or maybe use a dictionary

timber tide
#

Depends if you do want to develop these constructors, but I would just keep everything typed correctly

rich adder
vital vault
#

like one object (a gun for example) has properties like ammo left in clip, but a basket can have a list of items in it

vital vault
timber tide
#

Really just make as many structs/classes as you need

vital vault
#

no

#

not what i need

#
        {
            "Id":"Gun",
            "id":71929404,
            "pos":{
                "x":-7.31680632,
                "y":-1.62211561,
                "z":6.726395
            },
            "rot":{
                "x":-0.00672015827,
                "y":-0.9603869,
                "z":-4.31004446E-05,
                "w":-0.278589338
            },
            "data":{
                "ammo":12
            }
        },
        {
            "Id":"Basket",
            "id":-133609697,
            "pos":{
                "x":-5.947119,
                "y":-1.24142826,
                "z":7.639765
            },
            "rot":{
                "x":-0.000139048585,
                "y":0.999806643,
                "z":-0.0003319612,
                "w":0.0196609721
            },
            "data":{
                "items": [
                  {
                    "Id":"Gun",
                    "data":{
                      "ammo":12
                    }
                  }
                ]
            }
        }
#

thats what i meant

#

gun has ammo in its properties, and basket has another gun inside with 12 ammo

timber tide
vital vault
#

yeah what i meant

#

i think dictionary could work here

#

but can i make Dictionary<string, Object>?

rich adder
#

you can make Dictionary<string, object> sure

vital vault
#

and it will parse correctly?

rich adder
#

thats pretty much what Unity uses for Unity cloud for PlayerData

timber tide
#

newtonsoft yeah but JsonUtility follows similar editor serialization rules

rich adder
#

sum like this might be a lil cleaner though

public abstract class SaveObject {
    public string id;
}
//Gun
public class GunSave : SaveObject{
    public int ammoLeft;
    public int clipSize;
}
//etc.```

```cs
var objects = new List<SaveObject>();
objects.Add(new GunSave { id = "gun1", ammoLeft = 6, clipSize = 12 });
objects.Add(new BasketSave { id = "basket1", items = new List<string>{"apple","knife"} });
string json = JsonConvert.SerializeObject(
    objects,
    new JsonSerializerSettings {
        TypeNameHandling = TypeNameHandling.Auto
    }
);```
vital vault
#

so if i have

{
  "someShit": someOtherShit
}

it will parse down to

{
  "someShit": {
    "someOtherShitProperty":"xD"
  }
}
```?
hasty dragon
#

i made this scene to learn navmeshes, just two capsules, setting their destination to the target position it works fine, but am i getting frame drops and why does this scene have 8k tris

vital vault
#

but if be serious mark all immovable objects as static

timber tide
vital vault
#

it will save some drawcalls

hasty dragon
rich adder
hasty dragon
timber tide
#

can't say about the 8k tris (not a problem really) but turn on wireframe

rich adder
#

doesnt look like much going on visually to be slowing down

#

unless for some reason you really are building navmesh every frame, that'd be insane

#

Profiler will pinpoint the cause tho

hasty dragon
timber tide
#

capsules a little dense there

sour fulcrum
timber tide
#

lel, actually yeah unity capsules are pretty high poly

vital vault
hasty dragon
#

this is my first time using the profiler, i dont feel like the graph dancing like that is normal in a game with so little going on visually

rich adder
#

Deep Profiling also will show any code/methods as well

hasty dragon
#

i figured it out

#

whats semaphore wait for signal

rich adder
hasty dragon
rich adder
#

are those the only processes showing ?

hasty dragon
rich adder
#

weird normally is shows if its playerloop or editorloop

rich adder
#

so yeah its a symptom but not the cause

hasty dragon
#

what unity version do you use

rich adder
#

6.0.33f

hasty dragon
#

knew it

#

these issues started when i upgraded to 6.2

#

i never opened a profiler cuz i never found the need to

rich adder
#

could be , idk these "recommended" versions are pretty buggy

#

they're not final anyway

#

when 6.3 drops. 6.2 is already considered out of support

hasty dragon
rich adder
#

LTS are usually more stable

coral patio
#

Hey! We have a small minigame in our game where people have to click rather quick. We do play a hit sound. However we have the issue that sounds are quiet delayed after some time. In code I already added:

  • Instead of playing each per OneShot() over one audio source, i added a pool of audio sources and play the events over them (apparently thats better? but doesnt fix the issue)
  • changes audio to preload and PCM to maybe improve load time cuz i thought its bcs of that
  • added a small delay to play the sound

but doesnt matter what i do, it always starts lagging out after 10-15 clicks... not sure what else i could do here? i mean ego shooters play multiple sounds per second with weapons, i cant even get 10 to play in 2-3 😄

rugged beacon
languid pagoda
#

scratch that

#

my unity hub has not been updated

#

now there is a version without the security alert as well.

slender nymph
#

just update to a patched version

vital vault
#

if you are making a singleplayer game that dont pull anything you can just ignore it

languid pagoda
rich adder
#

no reason to update all my projects to a new unity version if I can just patch the binary

languid pagoda
languid pagoda
rich adder
#

updating all my projects when I know im on a stable version for me, I have no desire to update it any time soon

vital vault
#

but in my case, where i make games that only pull data that is being stored locally by the game itself it doesnt bother me

rich adder
#

as mentioned if need be, you can use whatever version is working for you then just use the patcher tool 🤷‍♂️

#

updating 30+ projects for me just to use a patched version of unity that may introduce possible bugs I never seen is nonsense when a binary patcher exists

languid pagoda
#

you're actively maintaining 30 different unity projects rn?

rich adder
#

ya bro lol

languid pagoda
#

thats crazy

#

i could never be bothered to keep up with that many

#

most of my code is unity packages instead for that reason

rich adder
#

doesn't help when you have adhd

#

a lot are collabs too, or client projects. I'm still trying to put something of my own on steam tho but that gets delayed by paid projects 😮‍💨

rich adder
#

(projects not editor)

#

not counting the ones on github that are not on disk 😅

visual pond
#

my

#

ball

#

(player) keeps bypassing the wall

#

they all have rigid bodys so whats wrong??

wintry quarry
visual pond
#

oh

wintry quarry
#

They also need to be moving via the Rigidbody

visual pond
#

but they have box colliders

languid pagoda
visual pond
#

is transform.position teleporting

#

or is it moving

#

thats probably why its going inside of it

solar hill
#

so its ignoring the collision

visual pond
#

dammit

#

so i have to use a forcemode?

solar hill
#

is the ball a rigidbody?

#

if it is a rigibody

move it using using velocity or using forces

visual pond
#

yeah it is

#

i have no clue how to use velocity lmao

#

only forcemods

eternal needle
#

setting the velocity can function the same as using addForce

rare hawk
#

I'm trying to make a custom Playable for Rigidbody movement. It's my first time extending the Playables API.
I thought I could just give every PlayableAsset a reference to a Mover and a position, and then when the PlayableAsset starts playing I make sure the Mover gets there in duration time. However, as I see it, there isn't really a method that gets called when a PlayableAsset starts playing? Both of my PlayableAssets CreateGraph() methods are fired when the PlayableBehaviour is loaded in, and not when the PlayableAsset itself starts playing

wintry quarry
#

But you can use AddForce or set the velocity directly, either is fine

blissful fable
#

https://pastecode.io/s/8kievjr7
https://pastecode.io/s/fh5afhsq
I. DO. NOT. UNDERSTAND.
How the fuck you are supposed to link two scripts.
No matter how hard I try, I always get NullReferenceException, and when I eventually find out what I had to do, I never really understand it.
Like seriously, look at the picture! How is it possible that it's reading the variable right, while also being a NullReferenceException at the same time 😭

#

How in the actual *@!$ can these two both happen in the same script?!

rich adder
blissful fable
#

No, I suppose not

rich adder
#

type t:PlayerHealth in the hierarchy searchbar

blissful fable
#

oh my god you were right 😭

#

Welp
Yeah I suppose that would be the only concievable explaination

#

I still really don't understand if there's a best practice when linking scripts

rich adder
#

looks fine to me

blissful fable
#

private PlayerSpawnManager spawnManager;
[SerializeField] private FirstPersonController fpController;

#

Like in my very script

#

I have to do two different types of methods to link scripts

#

But like

#

Why?!

rich adder
#

wdym two methods

blissful fable
#

One uses spawnManager = PlayerSpawnManager.Instance;
The other uses fpController = GetComponent<FirstPersonController>();

rich adder
#

GetComponent isn't necessary especially if its on the same gameobject , stick with [SerializeField] private and link through inspector

#

only times you can't do that is linking prefab/or spawned objects fields to scene components, usually passing it through simple DI or maybe using singleton like you have on the first line there

#

singleton makes more sense for things like a spawn manager or whatever managers and you only need 1

blissful fable
#

so I can use .Instance if the thing is actually in the scene?

rich adder
#

.Instance is just a static field you have created to assign it a specific Instance

#

assuming you assigned it in awake or whatever

#

you don't always want to make everything a singleton and use Instance

blissful fable
#

Gotcha

rich adder
#

GetComponent or my preferable TryGetComponent is pretty handy when doing some sort of runtime Get like a raycast hitting a collider and you want to check if it has the type you want

blissful fable
#

Is there actually a place where I can read all of the ways people use to link scripts, lol

rich adder
polar acorn
#

You can set a reference either in the inspector, or with =

vital vault
#

if im saving nested JSON parameter as object, can i just do serializer.Deserealize()?

foggy rapids
#

professor seems to not want to listen to me for help so i came all the way to the unity discord server

is there a way to call a variable in a game manager through a string? i want this script to be able to be used with various doors

rugged beacon
#

like a dictionary<string, your var thing>? but i think the door should know what key can be used on or key know doors can be used on instead of the game manager knowing the doors and keys

rugged beacon
wintry quarry
#

But basically, you're barking up the wrong tree most likely

foggy rapids
#

probably

wintry quarry
#

You can do what you want without the need for that

foggy rapids
#

changed to a switch case and i can do that

#

i will need to learn this properly eventually but i think this'll suffice for tracking wich keys i collected with one single script

boreal mason
#

Is there a channel for multiplayer related stuff?

wintry quarry
glossy turtle
#

@wintry quarry do you know any solution for this.

#

if i have a sprite image is it possible to animate without using animation feature

#

like the hand movement

wintry quarry
#

Sure why not

#

Just write code to do it. And/or use a tweener

glossy turtle
#

tweener is that free asset

night raptor
#

Tweener is something that does tweening. There are free tweeners yes

glossy turtle
#

ok thank you guys

#

will be checking tweeners now.

tiny island
#

what can i use in universal 2D to fadeIn/Out a sprite based on a collision?

hexed terrace
#

alpha on the sprite?
alpha on the material?

tiny island
#

how can i call the alpha of the sprite in C#?

sorry if it's a dumb question i'm new to unity

#

i'm trying to have a sprite with a 2D box collider have a event when my player enter in his box collider but it doesn't work , what am i doing wrong?

floral garden
#

add a log and see what it collide with or is it trigger

night raptor
tiny island
crimson arch
rugged beacon
#

at least 1 one object need rigidbody 2d

tiny island
#

it doesn't seem like the collision trigger itself works , i have my player with a rigidbody 2D and the sprite has a box collider Is Trigger so i don't know what i'm missing , would it be the scripting?

vital vault
#

but how can i make "polymorphism"?

#

basically diffirent objects have diffirent properties

#

and some have properties like objects inside of a container

rugged beacon
#

ngl i dont understand
you serialize the child and deserialize as parent?

cosmic dagger
tiny island
#

they are both 2D

rugged beacon
#

in same layer? when you remove the trigger does the 2 collide

cosmic dagger
tiny island
#

OnTriggerEnter/Exit2D

cosmic dagger
#

Do you have a log to check if anything collided?

tiny island
#

i don't understand how logs works

cosmic dagger
#

Also, does the other objects have a collider?

tiny island
#

the player has a rigidbody2D and the sprite has a box collider 2D

cosmic dagger
tiny island
#

i'm stupid

cosmic dagger
tiny island
#

i just added a box collider to player and now it works

#

the facepalm is real , tkx for the help

cosmic dagger
#

You can't tell if it collides without a collider. That's its boundary box . . .

worthy veldt
#

my enum method output becomes integer (enum index), even though i didnt cast it to int. this causes my if statement always false when comparing 2 enum

#

i used that same method to property return value and it worked just as I expected, so the method is fine.

#
public void CollectFloorItem(GameObject item)
{
    Location location = GetLocation(item.transform.position);
    
    for (int i = 0; i < areaScripts.Count; i++)
    {
        if (location==areaScripts[i].location)
        {
            //code never get through
            item.transform.parent = areaScripts[i].transform;
        }
    }
} 
#

its just a method to make the hierarcy clean

rugged beacon
#

if it same enum it would return same int too so it seem like the 2 doesnt equal

keen dew
# worthy veldt ```cs public void CollectFloorItem(GameObject item) { Location location = Ge...

Change it to this and show the console output:

public void CollectFloorItem(GameObject item)
{
    Location location = GetLocation(item.transform.position);
    Debug.Log("Location: " + location);
    
    for (int i = 0; i < areaScripts.Count; i++)
    {
        Debug.Log($"{i}: Comparing {location} and {areaScripts[i].location}");
        
        if (location==areaScripts[i].location)
        {
            Debug.Log("They are the same!");
            item.transform.parent = areaScripts[i].transform;
        }
    }
} 
worthy veldt
#

i have only set 1 area, repairshop is ites 11th element, and unidentified is 1st element

#
public Location GetLocation(Vector3 position)
{
    if (areas.Length <= 0)
    {
        Debug.Log("No area registered");
        return Location.Unidentified;
    }

    for (int i = 0; i < areas.Length; i++)
    {
        if (areas[i].bottomLeftBorder.position.x < position.x && position.x < areas[i].topRightBorder.position.x &&
            areas[i].bottomLeftBorder.position.y < position.y && position.y < areas[i].topRightBorder.position.y)
        {
            return areas[i].locationName;
        }
    }

    return Location.Unidentified;
} 
```this is getlocation
#

i set border gameobject on bottom left and top right (2D game), if the position is in between then its in the area

#

Areas is an array of struct, 2 border gameobject

keen dew
#

What are the types of areas.locationName and areaScripts.location?

cosmic dagger
worthy veldt
#

i just did actually, sec

cosmic dagger
#

Can you show us your enum file?

worthy veldt
#

roads is for npc teleportation onto another area, already worked

unique matrix
#

!vs

radiant voidBOT
# unique matrix !vs
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

naive pawn
#

hm, that looks configured?

worthy veldt
#

the one worked (OuterInn) is used in my npc thats spawning public AreaManager.Location CharacterLocation { get => AreaManager.Instance.GetLocation(transform.position); }

#

btw i also tried to cast both if ((int)location==(int)areaScripts[i].location), it doesnt go through

floral garden
#

hi, is it safe to delete .meta file ?

naive pawn
#

no

#

they are metadata used to link assets

floral garden
#

how can I clear it then? as it is placed in the main folder but if we move the script, it is in the still in the same folder

hexed terrace
#

it'll get regenerated as well - probably with different info that breaks links

floral garden
#

oh but if we don't have link?

hexed terrace
#

Unity cleans up the meta files itself

naive pawn
#

or you can move it yourself

floral garden
#

i am blocked on this, is it normal?

naive pawn
#

what led up to this?

#

an asset refresh, pressing play, etc?

floral garden
#

i don't know when I was texting there it got this , but well it is over haha

floral garden
naive pawn
#

depends on if you have auto asset refreshed enabled (which it is, by default)

#

if it's enabled, it'll refresh (& recompile) when you refocus unity

#

if not, it'll refresh when you refresh manually with ctrl+R, or also upon play mode iirc?

#

not sure on that latter part actually, i'll have to check

floral garden
#

it deosn't work rip even when I press refresh

naive pawn
floral garden
#

meta fils still there

naive pawn
#

those are all supposed to be there

hexed terrace
naive pawn
#

also this is definitely not a code issue

hexed terrace
#

those are the meta files for the folders

naive pawn
floral garden
#

yeah i know it but how can I make them move with the corresponding files ?

hexed terrace
#

they are where they're supposed to be.

floral garden
#

ok

unique matrix
#

anyone use linux mint with unity/visual studio code? i'm having trouble getting vscode to connect to unity as it says something like wrong slnx because dotnet only shows version 8 while wanting 9 and i've tried installing version 9 and 10 using a script from microsoft via the terminal but vscode still says i only have version 8 of dotnet installed, it was working fine last week. sorry if this isn't the right place to ask but idk where to

naive pawn
#

have you tried with the .NET install tool

#

also, just to make sure we're on the same page - vs and vscode are separate products, i saw you using the vs configuration command earlier

woeful trail
#

No I'm not into Linux I haven't had the time to learn that. I like moicrosofts operating system better

naive pawn
#

-# you can just.. not answer if you don't have any useful answer

unique matrix
#

i get 'ms-dotnettools.csharp: Trying to install .NET 9.0.11~x64~aspnetcore but it already exists. No downloads or changes were made.' and 'visualstudiotoolsforunity.vstuc: Trying to install .NET 9.0.11~x64 but it already exists. No downloads or changes were made.' on start up in vscode

cunning owl
#

Hello everyone, I have a question about the proper logic for my code in general
Let's say I have a player character in the scene that collects coin to gain money, is it better that the main code to collect the coin value is located in the player or in the coin ? Which one should collect the colliding data about the other ?

naive pawn
#

it's up to your design, really. either could work, but ideally it'd be consistent across different objects

unique matrix
#

i made the switch to linux last year which windows was easier but annoying. linux has only been troublesome when i update stuff, i should turn off checking for updates when things are running smoothly

naive pawn
#

consolodating all the logic in the player would probably be the easier option

naive pawn
cunning owl
unique matrix
#

i start up unity, double click a script to bring it up in vscode, it looks right but then shows an error in the bottom right and all the code loses half the colors with no autocompletion. in the output i get 2 messages of trying to install .net 9.0 but already exists

#

thats the error i get in the bottom right

#

it seems to be a recent error cause i only found 1 report of it online and a response within the last day

naive pawn
#

hmm the former error was about 9.0.11?

#

perhaps try uninstalling and reinstalling .NET

#

(note that nothing about that is saying you have .NET 8, you just don't have .NET 9.0.200 or above, apparently)

unique matrix
#

from the terminal i try 'dotnet --version' or 'dotnet --list-sdks' and says i have 8.0.121

naive pawn
#

are you using .NET for anything else?

unique matrix
#

even though i ran some script from microsoft to install 10 and 9

naive pawn
#

if not perhaps just uninstall everything and try installing again, with the .NET install tool in vscode specifically

unique matrix
#

not that i'm aware of. maybe stable diffusion

#

or video games

naive pawn
#

this is the .NET SDK, specifically

#

used for developing stuff, not for running stuff

#

so, do you have any other (non-unity) projects using C# or other .NET languages?

#

(that would maybe need different .NET versions)

unique matrix
#

nah, i don't do much scripting outside of gamedev

#

so i'll try uninstalling stuff and try again. worse case scenario i just wait for a patch, i think

naive pawn
#

and specifically don't use external installations

#

(not that that's bad, but using the .NET install tool has worked consistently, and there seems to be several things that can go wrong with external tools making them not link to vscode or something)

worthy veldt
# worthy veldt

i have found the cause, me commenting an element out messes with my stuff in the inspector, causing the border to have unassigned Location field.
someone said along the lines "then that means it returns null" before editing it out. i thought my enum cant be null and it will assign Unidentified as default... 11 is the unassigned enum

naive pawn
#

enums can't be null, yeah

cosmic dagger
# worthy veldt

definitely weird. i just ran a quick test and only received the 'correct' enum names when returning and comparing them . . .

naive pawn
#

commenting out the enum element makes all the values shift

#

unity serializes enum values based on their backing integral value

#

basically, enums are just integers with names

cosmic dagger
wintry quarry
#

or even if you did:

enum MyEnum {
  A,
  // B, 
  C, 
  D
}```
#

because the values will shift yeah

naive pawn
#

before, you had:

0: Unidentified
1: OuterInn
   ...
4: OuterCastle
5: InnerCastle
6: MeatShop
   ...
11: RepairShop
```after removing one of the elements,

0: Unidentified
1: OuterInn
...
4: OuterCastle
5: MeatShop
...
10: RepairShop

#

you generally don't want to be shifting enum members around, unless you specify a value for the members

wintry quarry
#

If you plan to shift/insert them you should give them explicit values and don't ever change them

#
enum MyEnum {
  A = 0,
  B = 1, 
  // C = 2,
  D = 3,
  E = 4
}```
#

C# lets you do this

naive pawn
wintry quarry
#

Then to insert one:cs enum MyEnum { A = 0, B = 1, F = 5, // C = 2, D = 3, E = 4 }

vale blade
#

does that mean everything has been loaded, and the scene just hasn't activated yet?

#

what happens in the remaining 10% ?

#

can that cause performance issues?

unique matrix
naive pawn
#

well if it breaks again, maybe try the instructions i gave

unique matrix
#

i didn't try that, i went through apt remove to uninstall which .net install tool probably wouldve done it cleaner

#

cause i still see 8.0 files lol

ocean quarry
#

Hello i want to make a classic mario game to test my beginner skills how to make a circle move tho the right or left and that a camera follows

#

its c sharp

keen dew
#

Test failed

#

You'll have to go back to tutorials and courses before trying to make it on your own