#archived-code-general

1 messages ยท Page 335 of 1

eager fulcrum
#

how can this be done?

plucky inlet
vagrant agate
#

You should look into Trail renderer or Line renderer to make your life easier for your behavior

eager fulcrum
vagrant agate
eager fulcrum
#

canvas

plucky inlet
vagrant agate
eager fulcrum
eager fulcrum
plucky inlet
#

What do the bars looklike inidivudally?

eager fulcrum
#

one sec

eager fulcrum
#

it looks like this

devout silo
#

I think

plucky inlet
eager fulcrum
#

i want to display the current mana when you hoover over the blue bar

#

and health when hoovering over the green bar

devout silo
#

The problem is not in the way I got the position and direction
The problem is with the lightning itself
It doesn't spin to the direction he needs to
@vagrant agate

vagrant agate
#

Are those 2 different images

eager fulcrum
#

yep

plucky inlet
eager fulcrum
#

yeah i know how to detect mouse hoovering

#

the problem is

#

that these 2 images overlap

eager fulcrum
old linden
#

I'm having an issue parsing json, now that I had added "ยฃ" to one of my fields. Is there any way around this?

plucky inlet
old linden
#

Im using Newtonsoft Json

heady iris
#

I presume it's trying to parse a float there

old linden
#

It fails on this line :/

heady iris
#

Show the JSON.

old linden
heady iris
#

that's invalid JSON

#

you can't stick ยฃ in a number

plucky inlet
# old linden

either use string instead or give an extra json property with currency or something

old linden
#

Ok thanks. Would it work if I wrap it in Quotes?

plucky inlet
#

than it would be a string and you would need to split it to get the number out of it

heady iris
#

right

heady iris
#
"Price": 123,
"Currency": "USD"
#

You don't win bonus points for cramming multiple things into a single value

plucky inlet
#

yep, agree, thats what I would do too

old linden
#

Yeah, seems like a better option. Thanks ๐Ÿ™‚

plain ibex
#

Why does the z value of my object change?
code is that:

bigMeteor.SetActive(true);
                float meteorPosX = Random.Range(0.2f,0.7f);
                Vector3 meteorViewportPos = new Vector3(meteorPosX,2,transform.position.z);
                bigMeteor.transform.position = mainCam.ViewportToWorldPoint(meteorViewportPos);
                lastSkillTime = Time.time;```
#

its changing to 11. but how ??

rigid island
#

make sure you account for depth

#

if is prospective you need nearclip plane

plain ibex
rigid island
#

Provide the function with a vector where the x-y components of the vector are the screen coordinates and the z component is the distance of the resulting plane from the camera.

plain ibex
opal mesa
#

Hi there! Is anyone using awaitables? in day to day life? Or are many using the asyncawait lib to use tasks in unity?
Just genuinely curious of what people use.

rigid island
plain ibex
rigid island
#

you dont need near clip in 2D

#

if your world object are at z of 0 then pass , 0

plain ibex
rigid island
#
var viewToWorld = ViewportToWorldPoint(etc..)
viewToWorld.z = 2```
plain ibex
#
bigMeteor.SetActive(true);
                float meteorPosX = Random.Range(0.2f,0.7f);
                Vector3 meteorViewportPos = new Vector3(meteorPosX,2,2);
                Vector3 meteorWorldPos = mainCam.ViewportToWorldPoint(meteorViewportPos);
                meteorWorldPos.z = 2;
                bigMeteor.transform.position = meteorWorldPos;```
#

so i do this

#

and its worked thanks.

supple rune
#

I am having issues with hitbox detection in my fighting game; it is not frame perfect. Take a 4 frame move, sometimes it hits on frame 5 and other times on frame 4. I believe this is due to the Unity animator being non-deterministic. How do I remove this inconsistency?

heady iris
#

the animator does not strictly operate on "frames"

#

if your game is running at 61 fps and your animation has 60 keyframes per second, then there will be one frame where you start and end between the same two keyframes

#

You can switch to "Animate Physics" on the animator to make it update in FixedUpdate. I suppose you could set your fixedupdate interval to match the target framerate.

arctic plume
#

Would anyone be able to help me with an issue I'm having with my code?
I have this script attached to a "falling platform" game object and I want it to spawn a new one in the original position after it has fallen

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (falling)
        {
            return;
        }

        if (collision.transform.tag == "Player")
        {
            StartCoroutine(StartFall());
        }
    }

    private IEnumerator StartFall()
    {
        falling = true;

        yield return new WaitForSeconds(fallDelay);

        rb2d.bodyType = RigidbodyType2D.Dynamic;

        yield return new WaitForSeconds(respawnDelay);
        Instantiate(platformPrefab, startingPosition, platformPrefab.transform.rotation);

        Destroy(gameObject, destroyDelay);
    }
knotty sun
#

So what is the 'issue'?

arctic plume
#

Sorry I completely forgot to elaborate, my bad haha
When the new one spawns it immediately starts falling (even though the player isn't on it) and it never spawns the next one

so the cycle goes: initial one when scene starts -> player lands on it -> falls -> new one spawns -> immediately falls for no reason -> no more platforms

knotty sun
#

I would presume it is falling because the rigidbody type on the prefab is incorrect

arctic plume
#

That's what I thought but in the prefab it says kinematic
But when the prefab spawns in-game it says dynamic, which I don't understand how (I guess that also explains why a 3rd one never spawns, because the coroutine never actually starts)

knotty sun
#

indeed, post the full !code

tawny elkBOT
leaden ice
#

Are you sure you're looking at the prefab and not some instance of it in the scene?

#

Make sure you have it straight in your head which is which, and importantly - which one your spawner code references.

arctic plume
# leaden ice Make sure you have it straight in your head which is which, and importantly - wh...

I double clicked the prefab from my project files to open it in the editor (so only the prefab is visible and nothing else) and double checked and it says kinematic

And I made sure to drag that prefab into the inspector field for the one in the scene hierarchy

I did notice that whenever I exit play mode, the field in the inspector gets renamed to itself, so for example the prefab is called "FallingPlatform", but the one in the scene is renamed to "FallingPlatform_1", then after I exit playmode, the game object listed in the inspector's field for the prefab also says "FallingPlatform_1", so maybe it's creating an exact copy of itself rather than an instance of the prefab, but again I don't understand why it would do that

#

I'll post the full code now

heady iris
#

If a prefab has any references that point to itself, those references are updated when you instantiate the prefab

leaden ice
knotty sun
#

sounds like you are overwriting the prefab reference with a gameobject reference

heady iris
#

So if the prefab has a reference to itself, it will create a copy of itself if it instantiates that object

#

rather than a copy of the original prefab

knotty sun
#

Ah, yes. is this code on the prefab?

heady iris
#

I wouldn't expect this to modify the name of anything after exiting play mode

arctic plume
#

Ohhh, that's annoying
So a prefab can't reference it's original unaltered self after being instantiated?

knotty sun
#

no

#

you need to get the prefab reference from another gameobject, a gamemanager perhaps

heady iris
#

or stuff it into a ScriptableObject asset that references the prefab

arctic plume
knotty sun
heady iris
#

Breaking the self-reference is awkward

knotty sun
#

There is one trick, make 2 prefabs

heady iris
#

A -> B -> A -> B -> ...

knotty sun
#

Exactly

heady iris
#

B could be a prefab variant of A, too

#

which would make it identical to A

#

still very silly, but that'll make it Just Work once you set the two up to point at each other

knotty sun
#

hackey but effective

arctic plume
#

I think I managed to get something to work, but I'm not sure if this is a "bad" solution haha, I would greatly appreciate it if either of you could provide feedback on it
https://hastebin.com/share/gigilavuku.csharp

knotty sun
#

not optimal but functional

raven basalt
#

Is this how you reset the object's position?

In the Awake() method, I have the following:

initialPosition = transform.position;

And then I try to reset the location through this:

            transform.position = initialPosition;

However, it doesn't seem to be working as the position doesn't seem to be reset

somber nacelle
#

does your object have a CharacterController on it?

raven basalt
#

no

#

It has a script that moves it though

somber nacelle
#

are you certain no other code or components are affecting its position?

#

because that absolutely would work provided the code is running and nothing else is interfering

clever bridge
#

Hi, this may not be the right channel, but when I start my game it now takes 2.5 seconds to change scene, and I don't know why, I went to the Profiler and paused the live play and found the frame where it took around 2500 ms but I don't know why it's doing it, is there a way to find out exactly what is causing it? This isn't super clear

plucky inlet
#

Do you guys have any recommendation for creating a timer? Any experience with System.Timer over Coroutine or Update with elapsed time check?

rigid island
#

each has their pros and cons

plucky inlet
rigid island
#

one thing I learned is using is yield waitforseconds is a bad way to do it UnityChanLOL
(too many inaccuracies / dependencies on framerate)

rigid island
plucky inlet
rigid island
pastel plover
#

A very stupid question

#

Anyone able to help with making character not fall through map?

#

(my eyes are shutting down, I am doing something wrong and cannot figure out for the life of me)

leaden ice
#

Also your MeshCollider is set to Is Trigger which makes it non-physical

#

As is your Plane's Box Collider

leaden ice
#

both colliders == triggers

#

therefore they are not physical colliders

leaden ice
pastel plover
#

Smh thats what they taught us at college

#

๐Ÿ˜ญ

leaden ice
#

๐Ÿ˜ฌ

pastel plover
#

So alright rigid body is getting deleted

#

Is trigger turned off

#

Convex is supposed to be on alongside providing contact right?

leaden ice
#

Honestly it's really sketchy having a MeshCollider on your character in any sense

#

especially if you're using CharacterController

#

With CC you basically don't want any other colliders on it at all

pastel plover
#

Aha

#

Do we need any collider on the ground?

leaden ice
#

yes

naive swallow
#

CharacterController is a collider, you don't need another one on that object

#

But you do still need colliders for it to collide with

pastel plover
#

I suppose this is good

#

For a plane

leaden ice
#

it's ok but it's probably too thin on the y axis

#

I would recommend making it at least .1 or ideally half a meter tall if possible.

swift falcon
#

What's the best way to replace tags like [PlayerName] in string dialogues?
I figured you can use string.Replace but i guess that would be pretty slow if you have to check for like 100 tags for every phrase

heady iris
#

computers are pretty fast, though

leaden ice
rapid flicker
#

hi, i have a horror gave and i need the monster to shoot object, but i tried to code someting for few hours and it doesnt woล•k, can someone share some script with me or help me in another way?

leaden ice
#

Every game is different

swift falcon
swift falcon
graceful laurel
#

when your using Proton servers callbacks the override gets called when what? dose it deped on the void name like on trigger enter or is it just the name o the void, if then when dose it get called?
using Photon.Pun;
public class ServerManager : MonoBehaviourPunCallbacks
{
public override void OnJoinedRoom(){

}

}

naive swallow
knotty sun
graceful laurel
#

ye but dose it depend on the name i just got it from a tutorial and it either gets called when idk what hapens or it depends on the name

#

i dont thinks its such a basic question

knotty sun
#

yes it is very, very basic

graceful laurel
#

then whoud you tell me the answer?

#

pls

naive swallow
graceful laurel
#

idk

#

probably not so much

knotty sun
graceful laurel
#

idc what its caled just want to know if the overides activates in a specific event or it depends on the method or whaterer.

#

cant you just answer me?

spark stirrup
#

What would be the best way to procedurally generate rocks that fit into my terrain? I need the rocks to be interactable so I can't use the built-in terrain features

rigid island
rigid island
spark stirrup
rigid island
#

you can also grab terrain data

naive swallow
#

Understanding how overrides work will let you understand the documentation enough to know when they are called

graceful laurel
#

thx

#

i fond the callback callbacks it suports and the server code thx for the override thats useful ๐Ÿ™‚

rigid island
pastel plover
#

Oh mb

rigid island
#

also formulate a full sentence before hitting enter ๐Ÿ˜‰

pastel plover
#

Sorry my bad, been working since 9 am almost all day haha

rigid island
#

all good! ๐Ÿ˜

orchid gust
#

Hey folks, I'm trying to make a class that holds data that I'll send between objects but the type of data that will be sent is different for different things, might be a Vector3 list or a string. Are there any types that can do tbat

heady iris
#

Can you give some more details?

rigid island
#

if you wanna send different types of class/struct make function take in Generic

#

maybe explain what you want to do exactly though

orchid gust
# heady iris Can you give some more details?

Say i have a sensor object and i want it to send data to a turret. I want to create a "IP packet" that contains the destination, source, protocol, and payload to send. So the Sensor sends a Vector3 List in the payload to the turret. But what is I also want another device to send a string in the payload to a signboard with the same idea. I need a way for the payload to take multiple types of information

heady iris
#

How does the turret know how to interpret the data it receives?

rigid island
#

can't the thing just have same methods with different overloads of types as param?

orchid gust
#

The Turret would see the protocol and know that the data is meant for it by interpretting the protocol, then it would read the payload

heady iris
#

in that case I'd make an abstract base class that has a field for the protocol, and then just downcast to a specific class (e.g. TurretTargetingProtocol)

#

or you could even just use is to check if the packet you got is the right kind

#
if (packet is TurretTargetingPacket turretPacket) {
  // ...
}
orchid gust
#

If im reading this correctly I think Im fine on interpretting portion, but Im having trouble with how to define the payload variable, but if what ur suggesting is the solution i may just be lost

heady iris
#

there is no payload variable here

#
public abstract class Packet {
  public int destination;
}

public class TurretTargetingPacket : Packet {
  public Vector3 target;
}
orchid gust
#

Oh so ur saying have each protocol be a class that holds its own payload

heady iris
#

yes, that seems the most tractable

orchid gust
#

Thats a great Idea thank you i can work with that

heady iris
#

If you were serializing this into data that actually goes over a network (or otherwise leaves the C# world), you would need to indicate which protocol you're using

orchid gust
#

none of that, just liking using the idea of networking inside the gamer

leaden ice
orchid gust
#

This way yeah, but the idea i was having at the time was just sending it with a class that just had a variable for destionation, source, protocol, and payload

dusk apex
#

You'd use !learn , the unity forums and the Discord server to assist in accomplishing your Unity task/game.

tawny elkBOT
#

:teacher: Unity Learn โ†—

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

jagged snow
#

I have random weights set up right now but what should I do when it gets chosen? There are 4 portals. When one gets picked I want that one to be less likely to get chosen, so how would I be able to do that? Do I simply divide 1 by the number of portals available? How would I be able to eventually bring it back to its original value when others get chosen?

lean sail
jagged snow
lean sail
jagged snow
#

Thats the thing so, I want to have it restore to its original value on it's own without needing extra functions of floats. I.e.
4 portals, 4 attempts, all 4 get chosen equally

leaden ice
#

it's kind of unclear what you're going for

#

how often "choosings" happen

#

etc

#

over time? Over a certain number of choosings?

jagged snow
#

Hmm I'll try to explain what the sequence should be:
There are 4 portals
One gets randomly chosen
The portal selected is 25% less likely to be chosen over others now.
If another portal is chosen the previous chosen portals chance is increased by 25% and the most recent chosen portal is reduced by 25%

#

I think what I need to do involves Lerping with normalized values. Theres a flat value and a normalized value

lean sail
#

whats stopping you from just reducing the weights by some constant factor or subtracting by a certain amount each time? Then increase by same factor.
Though if you do this a TON then eventually you're not gonna get the original values back due to floating point stuff

leaden ice
jagged snow
#

Sorry in order to make it simple I'll say each portal originally starts with 100% chance

leaden ice
#

that makes no sense

jagged snow
#

Acutally no I said that wrong, each portal has a flat value of 1

leaden ice
#

if there's 4, and they're all equally likely, they have a 25% chance

jagged snow
#

right

leaden ice
lean sail
#

you really dont need to lerp here either, you're overcomplicating this when its literally just division or subtraction, based on what you want.

leaden ice
#

if you want it to go from 25% -> 18.75% then you could do it this way:

You could do this by giving each element a weight equal to the number of elements.
So 4 elements, each gets a weight of 4.
When you pick the element, reduce its weight by 1.
So 4 -> 3.

3 / 16 is 18.75%

#

although that math doesn't math either

#

๐Ÿ˜จ

#

because it'd be 3/15 which is 20%

#

it really depends what you want >_>

jagged snow
#

when one of them gets chosen I apply a % modifier to the original value, since theres 4 objects. I remove .25f to the one thats chosen and add .25f to the rest.

#

Mathf.Lerp(0,maxFlatValue,normalized)

leaden ice
lean sail
#

I dont think you get back the original value by doing this in reverse though.

leaden ice
#

WHen I have 4 items, the chance for each is 25%.
When I select one, its new chance of being chosen should be what %?

jagged snow
#

The one thats chosen is based on its FlatWeight. So one could be 10 or 20.
Actually I see the problem with my approach now, because the ones with larger weights will get reduced alot more if they get chosen

leaden ice
#

Basically the total probability needs to add up to 1 (or 100%) So whatever you take away from one item, you need to redistribute equally amongst the rest to keep the percentages as desired.

jagged snow
#

My concern is that will these numbers go all over the place as things get chosen?

leaden ice
#

yes, the numbers will go all over the place.

lean sail
jagged snow
#

Does this mean I'll need to make min and max value for each one? I don't mind it but just askin

leaden ice
#

i don't really know what that means tbh

lean sail
#

same

jagged snow
#

like two floats for minChance and maxChance to prevent them from going too low or high

leaden ice
#

but how does that interact with everything else

jagged snow
#

Can one of them potentially go below 0?

leaden ice
#

the chance of an individual item being chosen will always be the weight of that item divided by the total sum of all the weights

#

so a min/max for a particular weight doesn't actually limit the chances of it being chosen in a meaningful way, since the total sum of weights is not bounded.

leaden ice
#

I actually think for a pool with N items, just starting them all with the weight N and decrementing that by 1 whenever it's chosen is the cleanest solution here.

#

and incrememting it (up to a max of N) whenever it's NOT chosen

lean sail
#

Really just try this with real numbers, step away from the whole theory aspect of it.
You have 4 weightings, 25 25 25 25. You pick a portal, what should values be, how should others values react. Do they scale up? Do they stay the same? This is all just in terms of what you want the chance to be.
The redistributing the values just means if you subtract 1 from any of the weightings, you now have a probability of 24/99. The rest are 25/99. So you add 1/(num portals -1) back into the rest.
1/3 = 0.33...
24 + 25.33 + 25.33 + 25.33 = 100
You dont even have to redistribute it properly, you could just simply remove a value and add to others

jagged snow
#

Sorry what does what does N mean?

leaden ice
#

N is the number of items

#

(4 portals in your example)

jagged snow
#

ah ok, I'm writing some pseduo code right now to try it out

lean sail
jagged snow
#

Also, to keep things simple I started with 4 portals with equal chance. However, in the future I might want special portals that have a higher base chance than others etc

lean sail
#

well then you need to decide strictly on how these weightings should be affected. Thats just more of a game design thought. For now, worry about getting it working and understanding the math

jagged snow
#

Alright will do, thanks!

#
{
    int[] weights = weightTable.Values.ToArray();
    int randomWeight = UnityEngine.Random.Range(0, weights.Sum());
    for (int i = 0;i < weights.Length; ++i)
    {
        randomWeight -= weights[i];
        if (randomWeight < 0)
        {
            return powerUpTypes[i];
        }
    }

    return PowerUpType.AMMO;
}```

Would do weightTable here need to be sorted based on it's value here from descending or ascending or would it not matter?
leaden ice
#

there's no need to sort it

#

I do think it needs to be randomWeight <= 0 though

jagged snow
#

thanks

jagged snow
#

Ok giving it a shot now,

    {
        int choiceIndex = GetRandomChoiceIndex(_choices.ToArray());
        float valueToRemove = _choices[choiceIndex] / _choices.Length;
        float valueToAdd = valueToRemove / _choices.Length - 1;

        Debug.Log($"Chosen Index: {choiceIndex} , Value: {_choices[choiceIndex]}, Value To Remove: {valueToRemove}");
        _choices[choiceIndex] -= Mathf.RoundToInt(valueToRemove);
        for (int i = 0; i < _choices.Length; i++)
        {
            if (i != choiceIndex)
            {
                _choices[i] += Mathf.RoundToInt(valueToAdd);
            }
        }
    }```

Not sure what I'm doing wrong as one value is going below 0 again
hidden flicker
#

how do i sort a raycastall by distance?

lean sail
hidden flicker
lean sail
hidden flicker
lean sail
#

there are built in methods for it. You can provide it the array which you should first try with basic numbers. Then for your RaycastHit[] you may need to provide it a comparer, which basically tells it what it should be using as a comparison value

hidden flicker
#

sick, thank you

#

should be able to get it from here :)

#

what's not working about my code?

cosmic rain
#

That's what we'd like to ask you. What doesn't work and what makes you think so?

#

Provide details in your message instead of linking to reddit.

hidden flicker
#

also, i see the problem but not the solution. it uses ARRAY.sort, but there doesn't seem to be a list.sort

cosmic rain
#

Did you look at the list documentation?

hidden flicker
#

can't find unity doc on lists

cosmic rain
#

Google "C# list API" or "C# list.sort"

#

Back to the basics: learning how to google

hidden flicker
#

got a solution from another discord

lean sail
#

you should really try to get more familiar with c# basics. lists and arrays are as beginner as it gets

velvet pebble
#

I'm getting a NullReferenceException when I try to add a newly constructed object to a list--```cs
_actionList.Add(new Utilities.InputBuffer(_playerInput.currentActionMap.FindAction("Jump")));

#
public class InputBuffer
{
    public readonly string Name;

    private float _timer;
    private float _duration;
    public InputBuffer(UnityEngine.InputSystem.InputAction action)
    {
        Name = action.name;
        Debug.Log($"{action}");
        //action.started += Action_started;
    }
    private void Action_started(UnityEngine.InputSystem.InputAction.CallbackContext obj)
    {
        _timer = _duration;
    }
    public bool Queued
    {get{return _timer <= 0;}}
}
#

the debug.log in the constructor is getting called, so I don't think there's a problem with the object itself

velvet pebble
#

DAMMIT

#

I forgot to initialize _actionList

leaden ice
velvet pebble
#

๐Ÿคฆโ€โ™‚๏ธ

#

thank you, I'll try to be more careful

chrome trail
#

I'm trying to create a script that "digs" into the ground in a spherical shape by transforming the mesh used to make up the ground. However, once I reach a certain depth, the mesh doesn't move.

I'm pretty sure the reason is because the vertices that have been warped are so far apart that the function meant to find the vertices doesn't see them, but I don't know how I would go about fixing this. So how can I fix this and is this even the right method to use to get what I want?

hollow dust
#

good evening, sorry if this is silly buy im using an interface to write my enemy take damage code and im wondering why my enemy character doesnt die, heres the code for the damage function and the interface code

#

    public void Damage()
    {
        //Health -= 50;

        for (currentHealth = 100; currentHealth > 0; currentHealth -= 50)
        {
            if (currentHealth <= 0)
            {
                Destroy(Enemy);
            }
        }

        //currentHealth = currentHealth - 25;





    }

#
public abstract class  EnemyStructure : MonoBehaviour
{
    public int currentHealth;


    //public float speed;



    protected abstract void Update();

  
    protected virtual void Attack()
    {
        Debug.Log("Enemy Class: Attack Method Called");
    }

}
#

he doesnt die after 2 hits

#

does anyone know whats wrong?

spring creek
hollow dust
#

before i used to have it randomly written in the function and realized everytime the function is called it resets the health to 100

#

so i put it in the for loop so that it doesnt

#

but im sure thats wrong lol

#

i just cant call it outside the function

#

or i can but its weird

spring creek
#

The loop is definitely not what you want

left adder
#

Someone here used photon before?
I have 2 players connected to 1 server, works fine, they can use the movement script perfectly well, but the sphere (body) falls to the ground and disapears for the other player (only visually) it still works well after that... but its wierd

spring creek
#

Damage should just reduce health, then immediately check if it is 0 or less

hollow dust
#

ah okay

quartz ruin
#

Hello, I would like some help. I want the order in layer jump to work correctly, and there are no parts where it doesn't work. I've attached the script for you to verify it thoroughly.

using System.Collections;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    public Sprite[] walkSprites;
    public Sprite idleSprite;
    public Camera mainCamera;
    public int minOrder = -1;
    public int maxOrder = 1;

    private SpriteRenderer spriteRenderer;
    private int currentSpriteIndex = 0;
    private bool isWalking = false;

    void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        spriteRenderer.sprite = idleSprite;
    }

    void Update()
    {
        Vector3 moveDirection = Vector3.zero;

        // Check for combined key presses
        if ((Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D)) || (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.S)))
        {
            StopWalking();
            return; // Stop movement if both A and D, or both W and S are pressed simultaneously
        }

        // Handle individual key presses
        if (Input.GetKey(KeyCode.W))
        {
            moveDirection.y += 1;
            if (!isWalking)
            {
                StartCoroutine(WalkAnimation());
            }
        }

hollow dust
#

    public void Damage()
    {
        //Health -= 50;


            currentHealth -= 50;

            if (currentHealth <= 0)
            {
                Destroy(Enemy);
            }
        
        //currentHealth = currentHealth - 25;





    }

#

like this?

spring creek
quartz ruin
# quartz ruin Hello, I would like some help. I want the order in layer jump to work correctly,...

secund part

 if (Input.GetKey(KeyCode.S))
        {
            moveDirection.y -= 1;
            if (!isWalking)
            {
                StartCoroutine(WalkAnimation());
            }
        }
        if (Input.GetKey(KeyCode.A))
        {
            moveDirection.x -= 1;
            spriteRenderer.flipX = true; // Flip sprite horizontally
            if (!isWalking)
            {
                StartCoroutine(WalkAnimation());
            }
        }
        if (Input.GetKey(KeyCode.D))
        {
            moveDirection.x += 1;
            spriteRenderer.flipX = false; // Don't flip sprite horizontally
            if (!isWalking)
            {
                StartCoroutine(WalkAnimation());
            }
        }

        transform.position += moveDirection.normalized * moveSpeed * Time.deltaTime;

        // Update camera position to follow the center of the sprite
        if (mainCamera != null)
        {
            Vector3 spriteBoundsCenter = spriteRenderer.bounds.center;
            mainCamera.transform.position = new Vector3(spriteBoundsCenter.x, spriteBoundsCenter.y, mainCamera.transform.position.z);
        }

        // Adjust sorting order
        int sortingOrder = Mathf.RoundToInt(transform.position.y * -100);
        sortingOrder = Mathf.Clamp(sortingOrder, minOrder, maxOrder);
        spriteRenderer.sortingOrder = sortingOrder;

        if (moveDirection == Vector3.zero)
        {
            StopWalking();
        }
    }

    private IEnumerator WalkAnimation()
    {
        isWalking = true;
        while (isWalking)
        {
            spriteRenderer.sprite = walkSprites[currentSpriteIndex];
            currentSpriteIndex = (currentSpriteIndex + 1) % walkSprites.Length;
            yield return new WaitForSeconds(0.071f); // Adjust animation speed as 

spring creek
tawny elkBOT
quartz ruin
#

ho, sorry again

#

emm, And now how do I share the page link?

spring creek
quartz ruin
#

okay

spring creek
#

But also, describe what is happening and what you want to happen, because

the order in layer jump to work correctly
Doesn't make any sense

quartz ruin
#

and... yea, i use chatgpt 4o for the codding XD

spring creek
buoyant vault
#

Anyone here knows about AssetBundling? How do I keep the files I download from a cloud bucket permanently, like how mobile games let you download them initially with a small size then download the remaining files after. Or does the app cache it by default if its from cloud?

quartz ruin
spring creek
#

This channel

#

I don't know why you posted it to a different channel at all

quartz ruin
#

i'm stupid

#

Can I send a better video? instead of photos

spring creek
#

Sure. But the pictures are pretty clear

#

You want to be in front of the wall on one side, and behind it on the other

#

I don't do 2d games like that, so I am not sure, but someone will know and can help

quartz ruin
quartz ruin
quartz ruin
#

I was also thinking of leaving it like this, and putting something like a blur to see through the walls, in the process the character would be seen

runic linden
#

Hey, I wrote a modular save game-system that uses this interface and a ScriptableObject as a data holder.

public interface ISaveDataItem
{
    public void SubscribeToSaveHandler();
    public void SaveData(SaveDataScriptableObject data);
    public void LoadData(SaveDataScriptableObject data);
}```
Now I'd love to have it like this instead, but this obviously does not work with interfaces:
```C
public interface ISaveDataItem
{
    public void SubscribeToSaveHandler()
    {
        SaveHandler.OnLoadData += LoadData;
        SaveHandler.OnSaveData += SaveData;
    }
    public void SaveData(SaveDataScriptableObject data);
    public void LoadData(SaveDataScriptableObject data);
}```
Is this just the trade-off that comes with interfaces or is there a way to easily force all instances of the interface to subscribe to the static events?
thin aurora
#

But this is odd in my opinion. I would assume you get all instances of ISaveDataItem and call the methods manually, not through an event?

#

Either that or you have a general singleton that has all persisting data

runic linden
runic linden
thin aurora
#

It's just the way the data is saved. How do you determine what object goes to which interface implementation?

#

Sadly an interface can't work like this in Unity so you'd have to do it manually in each constructor/awake method

runic linden
thin aurora
#

Another way would be source generation

#

Or lastly, run a method at the start of the game that fetches all instances through reflection and then hook them up from there stonks

#

Modern interfaces do have some support for what you want but idk if that works specifically

runic linden
lean sail
# runic linden That is possible but what's wrong with subscribing to a static event?

well the point of interface is so that you can directly call these methods as needed. You would store a collection of these objects like List<ISaveDataItem> and then call Save/Load. Right now you actually dont even need the interface. You could create a class like this

public class Something : MonoBehaviour
{
  void Start()
  {
    SaveHandler.OnLoadData += LoadData;
    SaveHandler.OnSaveData += SaveData;

  }
    public void SaveData(SaveDataScriptableObject data);
    public void LoadData(SaveDataScriptableObject data);
}

The only part of the interface that looks used is SubscribeToSaveHandler

chilly surge
#

But, I would strongly suggest to not use it. Most people consider this C# feature a mistake.

thin aurora
#

I don't think this works in Unity though

#

Unless the new version supports it

chilly surge
#

It does, DIM is a C# 8 feature and Unity supports C# 9 for a few versions now.

chilly surge
lean sail
#

Huh did my last message get blocked? well the message i tried replying to was deleted but i wrote "my class currently does everything your interface is capable of doing. Im just giving an example of why your interface isnt neccessarily needed."

runic linden
#

I deleted my message because I think I understood your approach ๐Ÿ˜…

quick spoke
#

yooi

#

Library\Bee\artifacts\WebGL \build\debug WebGL_wasm\buildjs: undefined symbol: ReleaseChannel (referenced by top-level compiled C/C++ code)

any idea about this error??

#

using photon

lean sail
runic linden
chilly surge
#

That's fine, explicitly listing out all the things you want to loop through is also fine.

runic linden
#

My thought process often is: I don't want to use FindObjectsOfType<T> too often for obvious reasons. I also sometimes don't know which objects will be there at runtime. Using static events seems to be the most flexible solution. Or not?

lean sail
# runic linden My thought process often is: I don't want to use FindObjectsOfType<T> too often ...

well im sure none of the suggestions here was gonna be FindObjectsOfType ๐Ÿ˜…. One simple change could just be like

public class SaveHandler
{
  List<ISaveDataItem> saveItems = new();

  public void RegisterSelf(ISaveDataItem saveItem)
  {
    // add to list
  }
}

and then instead of invoking the event, just loop through and call SaveData or LoadData. Also just realized its static but you probably can adjust for that

odd pecan
#

Hello, I'm trying to achieve this kind of screen wrapping so that it looks continuous instead of simply teleporting the player to the other side. I found a tutorial that uses this script and 3 cameras but I cant seem to get it to work. For some reason my right camera is showing on the left of the screen and its still snaps.


public class CameraCountinuousScreen : MonoBehaviour
{

    private float absScaleX; //abs scale of the sprite to get correct values
    private float colliderSizeX;



    private void Awake()
    {

        //current scale of our transform
        absScaleX = Mathf.Abs(transform.localScale.x);

        colliderSizeX = GetComponent<BoxCollider2D>().size.x;

    }

    void Update()
    {
       

        if (transform.position.x < Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)).x - (colliderSizeX/2 * absScaleX))
        {
            transform.position = new Vector2(transform.position.x + Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)).x * 2, transform.position.y);
        }

        if (transform.position.x > Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)).x + (colliderSizeX / 2 * absScaleX))
        {
            transform.position = new Vector2(transform.position.x - Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)).x * 2, transform.position.y);
        }

    }
}


runic linden
lean sail
runic linden
#

Thanks

odd pecan
odd pecan
#

nvm i cant figure out

odd pecan
#

I made some progress by setting the side cameras as overlay and adding it to the stack on the main camera. But now if I go too far in any direction it just snaps again, and I'm not sure why because it should snap only when it goes through the side the first time, if it makes sense

spring flame
#

is there a way somewhere to render scene view in editor to a 4K texture with a single button?

#

alternatively use scene camera to take a screenshot

buoyant marten
#

Hi i have a menu panel on my game project and im trying to add a PointerEnter event trigger to my UI Button to drigger an animation but when i assign the PlayButton to the proper field and from the dropdown i try to assign the proper method (OnPointerEnter) it does not appear in the dropdown. how do i fix this

Also here is my code

using UnityEngine;
using UnityEngine.EventSystems;

public class PausemenuPlayButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public Animator animator;

    void Start()
    {
        if (animator == null)
        {
            animator = GetComponent<Animator>();
        }
    }

    public void OnPointerEnter(PointerEventData BaseEventData)
    {
        animator.SetBool("MouseIsHovering", true);
    }

    public void OnPointerExit(PointerEventData BaseEventData)
    {
        animator.SetBool("MouseIsHovering", false);
    }
}
#

here i don't see the OnPointerEnter method...

knotty sun
buoyant marten
#

oh can you explain further ?

knotty sun
#

it's simple, you dont need to assign them to anything, the event system sees that you have subscribed and calls your methods when they fire

buoyant marten
#

ok so the whole event trigger component in my play button game object is unnecessary?

knotty sun
#

yes

buoyant marten
#

so remove this

#

sorry im asking dumb questions but i wanna make sure :DDD

#

and then the scene need a event system game component?

#

so here i dont have an avent system so i need to add that to the scene and it handles all automaticly?

knotty sun
#

All scenes need an Event System if you are using UI

buoyant marten
#

ok and when you create a canvas it creates a event system automatically i just deleted it cuz im stupid :DDD

knotty sun
#

that was, indeed, not advisable, Unity did not add one for no reason after all

buoyant marten
#

thank you this helped a lot :D

knotty sun
#

next time, instead of just doing random shit, go and read the docs first

odd pecan
#

i'm confused, Main camera is in the middle, why are there dots around the left camera and lines around the right camera. Also when I play it shows the right camera even if the main one has priority

buoyant marten
#

so now the event system automatically knows when im hovering on top of the button but how do i make the button do its hovering animation (button pulsates larger and smaller) when im howering on top of it. Any tips on that?

buoyant marten
#

Thank you :)

knotty sun
buoyant marten
#

got it

plucky holly
#

Hey. I wrote an editor script to add a button to my script and the function of the button is it gets the colliders size and set the value automatically. the button works well and the values changes when I press is, but the problem is when I Play, the values resets back to before I press the Auto-Align. How can I save the values that I change in Edit mode via script?

hexed pecan
#

You can also use Undo.RecordObject before changing the values if you want undo/redo functionality

plucky holly
#

ooh, what I tried was SetDirty(gameobject), but the right way is SetDirty(this)

plucky inlet
#

Quick question about disabling physics. As Physics.autoSimulation = false; is obsolete, I can`t really find the solution to not calculate physics entirely.

plucky inlet
leaden ice
#

Script mode is what you want.

#

It's the same

plucky inlet
#

Okay, thanks ๐Ÿ™‚ Just trying to crank out as much performance as possible right now ๐Ÿ˜„

pastel plover
#

Hey, got this code over here thats meant to make the player move around the map alongside rotate the model at appropriate directions. The rotations work fine but the corresponding asdw keys are not working properly. Any ideas how to fix this?

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
public float speed = 5f; // Movement speed
public float sprintSpeedMultiplier = 2f; // Sprint speed multiplier
public float sprintKeySpeed = 10f; // Speed when sprint key is held down

private void Update()
{
    // Get input for movement in the horizontal and vertical axes
    float horizontalInput = Input.GetAxis("Horizontal");
    float verticalInput = Input.GetAxis("Vertical");

    // Get sprint key input
    bool sprintKey = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);

    // Calculate movement direction based on input
    Vector3 movement = new Vector3(horizontalInput, 0f, verticalInput).normalized;

    // Modify movement speed based on sprint key input
    float currentSpeed = sprintKey ? speed * sprintSpeedMultiplier : speed;

    // Apply movement to the player
    transform.Translate(movement * currentSpeed * Time.deltaTime);

    // Rotate player based on camera's forward direction (optional)
    if (movement != Vector3.zero)
    {
        Quaternion targetRotation = Quaternion.LookRotation(movement, Vector3.up);
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 10f);
    }
}

}

tawny elkBOT
pastel plover
plucky inlet
#

Did you write this code yourself? And you should just learn to debug.log your stuff and understand every line of that code. If you do, you will get what is missing. Especially about the GetAxis part

pastel plover
#

More intrested in Cyber Security aspects of computing.

plucky inlet
#

Yeah, thats also the easier part about it structures ๐Ÿ˜‰ ๐Ÿ˜„

knotty sun
plucky inlet
#

Nice talk, cya ๐Ÿ˜„

eager fulcrum
#

hey, I have
public abstract class DialogueAction : ScriptableObject { }
and

[CreateAssetMenu(fileName = "UnitJoin", menuName = "DialogueActions/Unit Join")]
public class UnitJoinDialogueAction : DialogueAction { }

when i create asset for this it looks like this

#

why is there a "none mono script"

winter charm
# eager fulcrum

When you are working with Unity Scriptable Objects you should derive from Scriptable Object. public class UnitJoinDialogueAction : ScriptableObject

eager fulcrum
#

i need it to be derivering from DialogueAction

#

DialogueAction is a ScriptableObject

hexed pecan
# eager fulcrum

If UnitJoinDialogueAction is not in its own file with the same name as the class, you might need to do that

eager fulcrum
#

thanks ๐Ÿ‘

plucky holly
#

I've created a script that spawns the player at the position of the Scene View in Unity. I did everything and it works fine but I wanna make something better.

private void OnDrawGizmos()
{
    if (SetToView)
    {
        SceneView sceneView = SceneView.lastActiveSceneView;
        if (sceneView.in2DMode && sceneView != null && !Application.isPlaying)
        {
            Vector3 _Pos = sceneView.camera.transform.position + offset;
            if (_Pos != centerPosition)
            {
                centerPosition = _Pos;

                Gizmos.color = CrossColor;
                Gizmos.DrawLine(centerPosition + Vector3.down * crossSize, centerPosition + Vector3.up * crossSize);
                Gizmos.DrawLine(centerPosition + Vector3.left * crossSize, centerPosition + Vector3.right * crossSize);
                EditorUtility.SetDirty(this);
            }   
        }
    }
}

what is does is basically gets to position of the scene view when it changes and later I apply the position to the players position on Awake().
what I wanna do is make it a bit more optimized because it saves the centerPosition every single frame that position is changes. but I want it to only save (SetDirty) the position when I press the Play, just before the game is started and before the awake.

#

I used EditorApplication.isPlayingOrWillChangePlaymode before SetDirty.
I just wanna make sure if is there a better way of doing it

knotty sun
astral nexus
#

if I make my script as IPointerClick event for EventSystem - do I need to mark my background image as raycast target if it's a child of empty gameobject with this script to trigger it? Am I right that EventSystem triggers it's callbacks from child objects of trigger too?

inland lance
#

im working on a grappler in my 2d game, and just followed a tutorial where the guy sets the grapple to pull you in a certein length that you can choose. put i dont want that. so is there a way to make it so the grapple length to be set to the mouse position? because what i have tried has not been working

latent latch
hexed pecan
tawny elkBOT
inland lance
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GrapplingHook : MonoBehaviour
{
    private float mousePos;
    [SerializeField] private LayerMask grappleLayer;
    [SerializeField] private LineRenderer rope;

    private Vector3 grapplePoint;
    private DistanceJoint2D joint;
    // Start is called before the first frame update
    void Start()
    {
        joint = gameObject.GetComponent<DistanceJoint2D>();
        joint.enabled = false;
        rope.enabled = false;
    }

    // Update is called once per frame
    void Update()
    {

        if(Input.GetMouseButtonDown(0))
        {
            RaycastHit2D hit = Physics2D.Raycast(
            origin: Camera.main.ScreenToWorldPoint(Input.mousePosition), 
            direction: Vector2.zero, 
            distance: Mathf.Infinity,
            layerMask: grappleLayer);

            if(hit.collider !=null)
            {
                grapplePoint = hit.point;
                grapplePoint.z =0;
                joint.connectedAnchor = grapplePoint;
                joint.enabled = true;
                joint.distance =  mousePos;
                rope.SetPosition(0, grapplePoint);
                rope.SetPosition(1, transform.position);
                rope.enabled = true;
            }
        }

        if(Input.GetMouseButtonUp(0))
        {
           joint.enabled = false;
           rope.enabled = false;
        }

        if(rope.enabled == true)
        {
            rope.SetPosition(1, transform.position);
        }
    }
}
inland lance
hexed pecan
inland lance
#

yes

hexed pecan
#

This doesn't seem to cast the grapple from the player, it just checks if there's an object where you clicked ๐Ÿค”

#

What type of 2D game is it? Like what perspective

inland lance
#

platformer

hexed pecan
#

i would use
-origin: Character's position (or hand position)
-direction: mouse world position - origin
-distance: magnitude of direction

#

If you want to cast it from the character and not be able to grapple inside a wall

inland lance
#

ok

#

ill try that thank you!

#

wait where should i use that in the code?

hexed pecan
#

Those are the parameters for the Physics2D.Raycast

inland lance
#

alr thank you

#

it dosent seem to be working..?

inland lance
knotty sun
inland lance
#

what?

knotty sun
#

what you posted as code is not code

inland lance
#

check the code above thats what i had the syntax is what osmal gave me to help with my problem

knotty sun
#

what Osmal posted is pseudo code, you are supposed to use your initiave and fill in the blanks (or non code bits)\

inland lance
#

oh

#

ok sorry and thank you ill try doing that

#

again kind of a begginer

knotty sun
# inland lance again kind of a begginer

Sorry, even a raw beginner should know that 'Character's position (or hand position)' is in no way valid code
if you do not then I suggest you learn C# basics

inland lance
#

yeah i figured that part out

#

didnt know that other parts

#

i know c# basics

#

its the other part

vagrant blade
#

Even with C# basics, you would know "magnitude of direction" is not valid code either.

inland lance
#

thank you

void void
#

Hi, I'm introducing Assembly Definitions in my project however I'm encountering some issues.
I've referenced most of the assemblies I use but I can't seem to find an assembly corresponding to System.Collections.Generic so I'm getting this error: The non-generic type '...Authoring.Baker' cannot be used with type arguments
Is there an Assembly Reference I'm missing or is it something else ?

thick terrace
plucky inlet
#

When you duplicate a gameobject in the scene, is there any event that gets called inside unity that tells you, this object is "new"? I am trying to keep consistent guids for gameobjects but when copying lets say a prefab with an id predefined, i want to assign a new guid, otherwise all prefab instances would use the same.

naive swallow
#

This is not consistent between sessions so you wouldn't gain much by storing it, but you could check for differences to know if two objects are unique instances of the same prefab

thin aurora
#

This error is weird

heady iris
thin aurora
#

Either way the error is shown because it did find System.Collections which contains non generic types

heady iris
#

I hadn't thought of that before. That might actually be enough to detect being instantiated

plucky inlet
void void
#

The Assembly Definition that encompasses the relevant scripts

west knot
#

I am trying to use Splines, but when I try to find the nearest point on the spline i keep getting a point of (0, 0, 0) then suddenly it switches to a different point as seen in the attached photo. It will be like A for some period of time then suddenly switch to what B says (B changes as the object moves).

Follow Path logic (currently only get nearest point for the PID Controller) --> https://hatebin.com/tbfalfiege

Object movement logic (for testing) --> https://hatebin.com/cbgqqzufnh

heady iris
#

one important thing to note is that you get a position on the spline -- not in world space

#

notice that GetNearestPoint takes an ISpline, not a SplineContainer

#

Try transforming this point into world space

#

(using the transform of the spline container)

west knot
#

i did find that out, however it gives me the point on the spline of (0, 0, 0) for a while then suddenly switches

heady iris
#

You also need to transform your world-space position into the spline's space when passing it in

west knot
#

I did not do that

heady iris
#

I presume your world space position winds up behind way behind the start of the spline in its own space

#

hence all the [0,0,0] results

west knot
#

that makes sense,

heady iris
#

Anything that uses a SplineContainer is world-space; anything that uses a Spline is in the spline's own space

west knot
#

Ok i'll look into how to do that transformation

#

oh, interesting

heady iris
#

splineContainer.transform.TransformPoint goes from local to world, and InverseTransformPoint is the opposite

west knot
#

ok thanks, I will have a look into that, that does seem to be the issue, world/local points

heady iris
#

I found this to be confusing when I was learning to use Splines!

#

a spline doesn't exist in the world on its own, which is why anything that uses a spline is done in the spline's own space

#

a spline container does exist in the world

west knot
#

the knot coordinates listed in the spline container are in the splines coordinate system it seems, corretc?

heady iris
#

Right.

#

So moving the entire container around does not change the spline data at all

west knot
#

ok, i get what is going on now, seems like a weird way to do it.

heady iris
#

it's equivalent to how you animate the local rotations of an armature's bones, not the world rotations

#

otherwise the animation would change (and go horribly wrong) as you rotate the armature

west knot
#

ahhh yes ok got it

#

@heady iris Thank you for the help, I'm going to go and get this all working hopefully ๐Ÿ™‚

chrome trail
#

So I heard about this thing called "marching cubes", but I'm not really sure I understand it. What I understand is it's supposed to be a bunch of vertices that each represent a cube that can be turned on and turned off via some kind of binary code, but I don't understand how that code is calculated or how it determines what cubes are turned on and which are turned off

heady iris
#

there are quite a few tutorials about the process; have you followed any of them?

#

I also don't really get it yet, but I also haven't tried to actually implement it

chrome trail
heady iris
#

catlikecoding has a series on marching squares

#

the first part talks about the bitmasking

#

All you're doing there is looking up a mesh based on which vertices are filled in

#

with four vertices, you get 16 configurations

#

(including some with rotational symmetry)

#

I presume that, for marching cubes, you have 8 vertices, and thus 2^8=256 possible configurations

#

(exponential growth gets big quickly)

#

for marching...lines, you'd have 2 vertices with 4 configurations

kindred scaffold
#

Hello! I need help understanding why OnTriggerStay2d is being called twice.
Here you can see when my player is standing on the edge of the composite tilemap collider, the OnTriggerStay2D is called twice, but it is find when the player is standing in the middle of the composite tilemap collider
(Using Outline mode gets this behavior. using polygon mode yields the exact opposite behavior)

knotty sun
#

OnTriggerStay is called every frame that the colliders intersect

kindred scaffold
#

I know that, as you can see it's being called twice in the same frame

#

the debug logs are collapsed and show (2) on the same exact fixedtime

naive swallow
knotty sun
kindred scaffold
#

ah ok

#

my bad it was indeed 2 colliders on my player

#

though i do have another question now, shouldnt this prevent calling ontriggerenter twice?

#

and is there a way to have a collider ignore/not be detected by all trigger colliders?

#

okay nevermind i figured out my own solution, thanks guys!

swift delta
#

what would you say is better for detecting if a character is grounded in a sloped 3D environment:

  • a collider using OnTriggerStay
  • raycast detecting the ground
  • spherecast detecting the ground
swift delta
#

what are its advantages vs ontriggerstay?

#

haven't had much luck googling the differences

rigid island
#

ontriggerstay is not as reliable

#

plus you would have to make a sepearate collider just for it

swift delta
#

or a variable being brought over from a different script in my case I guess

rigid island
#

doesn't handle multiple surfaces as well, you don't get details about ground you hit (if you need slope angles etc)

swift delta
#

I'll give the spherecast a fair shake

#

thanks for the help

latent latch
swift delta
#

I just need to check if there are any ground colliders whatsoever, not doing something to each one in an array

latent latch
#

spherecast doesnt work if the cast originates inside of another collider

#

unless you are to say cast it above your pivot downward

swift delta
#

seems to be detecting it just fine. just needs some radius tweaking

latent latch
#

It can work but written on the docs it even says
Notes: SphereCast will not detect colliders for which the sphere overlaps the collider. Passing a zero radius results in undefined output and doesn't always behave the same as Physics.Raycast.

#

I was just dealing with a similar issue I couldn't melee something with my guy because I was too close with it cast

#

and the fix to that is to use both overlap and spherecast

rigid island
#

yeah I recall a while ago having to switch it to overlap for similar reason

#

checksphere also works for simple usecases (when you don't care about raycasthit)

swift delta
#

I'm already running into issues visualizing the best way to detect the ground at any rate

#

such as where exactly I should be positioning the sphere and how large it should be

rigid island
swift delta
#

yeah I'm just trying to think of this exactly:

#

let's assume I cast the sphere like this

#

I think it would work in theory, but where should I be casting it so my character doesn't just float a bit off the ground?

#

alternatively, if I do this...

#

would I need to do a cooldown when the character jumps so they can't jump again right after that?

rigid island
#

so you can play around with it in test mode, see what fits best your character

swift delta
#

I tried that, but I think the gizmos were not being updated in real time

#

either that or I screwed up the code

rigid island
#

prob 2

swift delta
#
void OnDrawGizmos()
    {
        Gizmos.DrawSphere(groundCheckPos, sphereRadius/2);
    }
#

don't mind that /2

#

I got the size but called it the radius and realized that later

rigid island
#

groundCheckPos is what exactly ?

swift delta
rigid island
#

where do you set it though

swift delta
#

in update.

    playerHeight = groundCollider.size.y;

    // (...)

    groundCheckPos = groundCollider.transform.position + groundCollider.center;
    groundCheckPos.y = groundCheckPos.y + (playerHeight / 2) - 0.1f;
#

groundCollider is a box collider

#

playerHeight is a float being set in the inspector

#

ah, wait, no it isn't. I changed that to use groundCollider's bounds

willow meteor
#

hey guys, is there a way of applying shadows to a tmp text? cant seem to get it working. i believe its because the text material has color set to HDR but i cant find a way of disabling it, any ideas?

latent latch
#

no really a coding question, but on the text component you can open the shader options at the bottom to mess around with colors and other options

#

not too sure about shadows though as that may be something not included in it

leaden ice
#

AFAIK the material it uses is unlit by default

#

you'd need a shader that takes lighting into account

willow meteor
#

yeah ive tried every shader that comes with tmp package

#

even the extras

#

but every color is locked to HDR

latent latch
#

it's actually like 3 lines of hlsl code to do if you do want to edit the whole dang shader

#

actually would probably break a bunch of stuff

willow meteor
#

oh..

latent latch
#

legacy text and a custom shader is what I'd do

swift falcon
#

Does anyone think they can help me with Developing a Wall placement and Room Building System like in Sims 4?

rigid island
#

@swift falcon

swift falcon
#

but isnt this the Code Channel?

rigid island
#

do you have a specific confusion on building system ?

#

your question is very vague

swift falcon
rigid island
#

oh you mean extruding the walls ?

placid summit
#

You need to code such a system but it's a very big task. I would learn about the Mesh class first to generate meshes

swift falcon
rigid island
#

yeah pretty much you need to learn building meshes

#

I think the older ones were easier to replicate then new one

swift falcon
rigid island
#

nah like the older sims building system

#

iirc sims 1 was just tiles

swift falcon
#

But isnt sims 4 tiles too?

rigid island
#

the wall building to me looks like it builds a mesh/modifies it as you pull the arrows n whatnot

#

its still grid based ofc

swift falcon
#

well do you know any ways I could start with the basics of one closer to Sims 1?

rigid island
#

lots of boolean operations probably for walls and windows

placid summit
rigid island
#

yeah thats beyond what my monkee brain can handle

cyan heart
#

Hey I'm really new to unity (the code-beginner channel is being used) and atm I have a 2d game with a gameObject that has a few children with sprite renderer components and one tmp text.
I have the script set up to make it fall and spin and that all works but I can't figure out how to make it clickable.

leaden ice
latent latch
#

some raycasting method usually

leaden ice
#

A slightly better way would be to use the event system's IPointerDownHandler - which will allow itself to be blocked by UI elements, among other advantages.

cyan heart
#

ok and to use the onMouseDown I need to attach a collider to the object right? Is that all it takes or do I need other stuff with the camera raycast things? I googled it and got a lot of different answers

leaden ice
#

I assumed you had one already with your description of it falling and stuff

#

It only needs a collider for OnMouseDown

latent latch
#

raycast logics usually need a collider to detect something 'hitting' it

leaden ice
#

for IPointerDownHandler you need other things too, but that's a different approach

cyan heart
#

no lol I just moved it all manually and once it's y was below a point I just deleted it.

#

so if I have a lot of cards falling and they might overlap would the onMouseDown approach be fine? Like does the IPointerDownHandler do something important in the context of my simple game?

dawn nebula
#

The materials on Images don't seem to create a new instance when you access them.

#

Compared to renderers.

hardy meadow
#

Does anyone have any tips for making code/features more modular, or can point me in the direction of resources that point these out? I'm currently running into some tightly-coupled-mess issues which I want to prevent in the future

placid summit
dawn nebula
#

Gotta create my own.

placid summit
#

Yes not very consistent but as you say you can duplicate and apply new

latent latch
gleaming island
#

hi

rancid frost
#

How does this boundsInt not contain the vector3 position (0,0,0)???

heady iris
#

It's an exclusive upper bound

#

that's necessarily because otherwise it'd be impossible to create a bounds that contains nothing

rancid frost
#

I see

rancid frost
cosmic fable
#

Hi, i am trying to make a teleportation script, but it doesn't want to work, it works for one frame, you can actually see the destination, but then you are snapped back, if i send someone my code, or my project can someone please try and fix it?

spring creek
lean sail
tawny elkBOT
cosmic fable
cosmic fable
#

@spring creek is that an issue?

lean sail
cosmic fable
#

ah, how can I do that?

lean sail
spring creek
cosmic fable
#

I fixed it, thank you so much!

#

I might still have a chance yet

devout nimbus
#

Destroy(gameObject);
Destroying assets is not permitted to avoid data loss.

why would this ever result in that error? It is a script on a gameobject. The script does have references to scriptable objects and such but just destroying the gameobject itself shouldnt result in an error thinking im wanting to remove an asset from my library right?

lofty field
devout nimbus
#

I think I got it actually, just wrong order of instantiating something that exists on a prefab

lofty field
#

I added this to the chessboard script, this just shows where i added the history panel stuff, Now im trying to to figure out how to make it look right in the UI like scroll view, any suggestions?

    public GameObject moveHistoryPanel;
    public Text moveTextPrefab;

    private List<string> moveHistory = new List<string>();

    private void OnMakeMoveServer(NetMessage msg, NetworkConnection cnn)
    {
        // Receive the message, broadcast it back
        NetMakeMove mm = msg as NetMakeMove;

        // Add move to history
        AddMoveToHistory(mm);

        // Receive, and broadcast it back
        Server.Instance.Broadcast(msg);
    }

    private void OnMakeMoveClient(NetMessage msg)
    {
        NetMakeMove mm = msg as NetMakeMove;

        // Add move to history
        AddMoveToHistory(mm);

    }

    private void AddMoveToHistory(NetMakeMove mm)
    {
        // Add move to history list
        string moveString = $"Team {mm.teamId} moved from ({mm.originalX}, {mm.originalY}) to ({mm.destinationX}, {mm.destinationY})";
        moveHistory.Add(moveString);

        // Update move history panel
        UpdateMoveHistoryPanel();
    }

    private void UpdateMoveHistoryPanel()
    {
        // Clear existing text objects
        foreach (Transform child in moveHistoryPanel.transform)
        {
            Destroy(child.gameObject);
        }

        // Add move text objects
        foreach (string move in moveHistory)
        {
            Text moveText = Instantiate(moveTextPrefab, moveHistoryPanel.transform);
            moveText.text = move;
        }
    }
lean sail
lofty field
#

not showing up in the scroll view...

#

I get this error when I try to move MissingReferenceException: The object of type 'TMPro.TextMeshProUGUI' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object. Parameter name: data
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <240ff6271d47469a95269de220922c38>:0)
UnityEngine.Bindings.ThrowHelper.ThrowArgumentNullException (System.Object obj, System.String parameterName) (at <240ff6271d47469a95269de220922c38>:0)
UnityEngine.Object.Internal_CloneSingleWithParent (UnityEngine.Object data, UnityEngine.Transform parent, System.Boolean worldPositionStays) (at <240ff6271d47469a95269de220922c38>:0)
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Transform parent, System.Boolean instantiateInWorldSpace) (at <240ff6271d47469a95269de220922c38>:0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Transform parent, System.Boolean worldPositionStays) (at <240ff6271d47469a95269de220922c38>:0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Transform parent) (at <240ff6271d47469a95269de220922c38>:0)
MMM.Chessboard.UpdateMoveHistoryPanel () (at Assets/Scripts/Chessboard.cs:1081)
MMM.Chessboard.AddMoveToHistory (NetMakeMove mm) (at Assets/Scripts/Chessboard.cs:1067)
MMM.Chessboard.OnMakeMoveClient (NetMessage msg) (at Assets/Scripts/Chessboard.cs:1048)
NetMakeMove.ReceivedOnClient () (at Assets/Scripts/Net/NetMessage/NetMakeMove.cs:54)
NetUtility.OnData (Unity.Collections.DataStreamReader stream, Unity.Networking.Transport.NetworkConnection cnn, Server server) (at Assets/Scripts/Net/NetUtility.cs:41)
Client.UpdateMessagePump () (at Assets/Scripts/Net/Client.cs:93)
Client.Update () (at Assets/Scripts/Net/Client.cs:67)

#

added a debug, the error now is Move text prefab is null. Cannot instantiate move text objects.

    ```private void UpdateMoveHistoryPanel()
    {
        // Check if the moveTextPrefab is null
        if(moveTextPrefab == null)
        {
            Debug.LogWarning("Move text prefab is null. Cannot instantiate move text objects.");
            return;
        }

        // Clear existing text objects
        foreach(Transform child in moveHistoryPanel.transform)
        {
            Destroy(child.gameObject);
        }

        // Add move text objects
        foreach(string move in moveHistory)
        {
            TMP_Text moveText = Instantiate(moveTextPrefab, moveHistoryPanel.transform);
            moveText.text = move;

            // Add click event listener for move replay
            moveText.gameObject.AddComponent<MoveReplayClickHandler>().moveString = move;
        }
    }```
lean sail
lofty field
#

without the move history panel the moves show up in debug

#

I think i might have forgotten to name the move text prefab right

lean sail
#

well i cant see your entire setup, but i dont know what you mean by "name the move text prefab". If something is null, you likely just didnt assign it a value yet.
Are you using AI also?

lofty field
#

no ai for game yet... watching a video on minmax algorithm

lean sail
#

No, i meant are you using AI to code.

lofty field
#

if you have a couple minutes, I have my own server, I can live stream my screen????

#

I code from reading and watching videos

lean sail
lofty field
#

I have it set for a tmpro, but i want it to be a scroll view, which isnt tmpro, so i have to recode i think??

lean sail
#

I suggest you dont copy the code then so much, and try to actually understand whats happening. Because the issues you are describing, like null or MissingReferenceException are really quite beginner. Yet you seemingly have a lot of code since that error was on line 1081

#

if moveTextPrefab is null then you probably want to assign it to a prefab containing text, that moves. not a scroll view

gray nebula
lofty field
lean sail
#

Are you trying to set it from an EditorWindow?

#

i notice the link you posted also does use .animationClip, is there something specific that wasnt working?

gray nebula
lean sail
#

otherwise there isnt really much that can go wrong here

gray nebula
lean sail
#

whenever you get around to solving it

gray nebula
rigid island
#

or just use LFS. its up to you

soft shard
#

Ive recently been dealing with a similar issue but for textures and audio files, the suggestion I ws given was to use git for just code files and engine-specific files (like scenes, prefabs, scriptable objects, etc) and all imported assets like models, textures, audio (in your case, plugins) should be a part of a secondary cloud storage like Box or something that is intended to support more space, git (at least the free plan) supports I think 2GB or 4GB for your entire project, so files that weigh 100+ MB will eat that limited space, LFS offers an additional I think 1 GB or 2GB of storage for those large files, but its not really a "solution" imo since it will fill up fast... The downside of a second cloud storage though, is you lose any asset references that prefabs or scene objects might have had, unless you re-reference them by their file paths and push their file paths with your commits, that means those assets need to be imported in your project before you open the project, cant say either is an ideal approach but its the one ive been suggested recently

left adder
#

Hee, I had a code issue but it included photon, I posted it in #archived-networking but maybe it should be in here? Not sure ๐Ÿ™‚

terse pier
#
public class WaitForAnimation : CustomYieldInstruction
{
    private Animator animator;
    public override bool keepWaiting => animator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1;
    
    public WaitForAnimation(Animator animator)
    {
        this.animator = animator;
    }
    
}

Anyone know why it is not waiting for the animation to finish in my Coroutine

terse pier
# plucky inlet What coroutine?
    public IEnumerator ShootCoroutine(EntityType entityType)
    {
        hasPicked = true;
        Entity target = GameManager.Instance.GetEntity(entityType);
        if (target != null)
        {
            target.animator.SetTrigger("Pressed");
            if (entityType == this.entityType) target.animator.SetBool("Is Self", true);
            else animator.SetTrigger("Aim At Target");
            yield return new WaitForAnimation(target.animator);

        }
        yield return new WaitForSeconds(1f);
    }
thin aurora
plucky inlet
thin aurora
#

Just taking reference from this, idk if this would fix it

thin aurora
terse pier
#

omg...

thin aurora
#

Or I'm wrong, I'm not exactly awake

lean sail
#

they would have to be resetting something, the method by itself does nothing. but i think the current < 1 is correct because you want to keep waiting while its not 1

#

I also wonder what indicates to you that this isnt working, because this coroutine does nothing after waiting

terse pier
# lean sail I also wonder what indicates to you that this isnt working, because this corouti...

it does something, it really isn't relevant enough...

    public IEnumerator ShootCoroutine(EntityType entityType)
    {
        hasPicked = true;
        Entity target = GameManager.Instance.GetEntity(entityType);
        if (target != null)
        {
            target.animator.SetTrigger("Pressed");
            if (entityType == this.entityType) target.animator.SetBool("Is Self", true);
            else animator.SetTrigger("Aim At Target");
            yield return new WaitForAnimation(target.animator);
            bool isBullet = GameManager.Instance.Shoot();
            if (isBullet)
            {
                target.animator.SetTrigger("Hit");
                target.Die();
                yield return new WaitForAnimation(target.animator);
            }
            bool keepTurn = (target == this && !isBullet);
            
            if (entityType == this.entityType) target.animator.SetBool("Is Self", false);
            target.animator.SetTrigger("Normal");
            animator.SetTrigger("Normal");
            hasPicked = false;
            GameManager.Instance.StartTurn(keepTurn);
        }
        yield return new WaitForSeconds(1f);
    }
lean sail
#

Ah i see

terse pier
#

doesn't even get there

lean sail
#

have you checked that the animation is fully playing? If its going between 0 and this 0.0166.. then that might indicate its constantly playing the start of one

#

You might even want to store the AnimatorStateInfo and then check if its the same as the initial one.

terse pier
#

Ah i see what's going wrong

#

it stops because the animation it was originally playing finished

#

so i would have to wait like 0.01s extra

lean sail
#

You just need to tie into that OnStateExit

fleet gorge
#

or have a animator event at the end of the animation

#

kinda dumb to hardcode your anim duration into your code

lean sail
#

I think animation events are even worse ๐Ÿ˜…

terse pier
#

I'll check it out

terse pier
lean sail
#

You might really wanna do testing with what i linked, because I havent used it other than once for testing. I saw something online about OnStateExit not being called if it loops but that was an old thread.

#

Also i dont know what they meant because you didnt code the animation duration anywhere, normalized time is fine.

fleet gorge
#

not you

#

but like

#

lets just say I worked with programmers whos entire code is like that

terse pier
#

Animations in general are pain and imo there is no right way to have animations, besides not having them.

lean sail
#

i enjoy animations a lot more when im just doing my logic alongside them, rather than trying to tie into animation events.

#

It also lets me just easily swap out animations, because i never had an event associated with it in the first place. All I declare in editor is when in the normalized time something should happen (ex: at 0.5 or 50% through the animation). Then start a timer and do my logic after that timer reaches 50% of the total length, which i also use a speed multipler for so the animation takes the total length i declare in editor.

latent latch
#

I usually have some timer sync'd to my animation time when I play it so I just refer to that

#

I was trying to use those animation events earlier, but I needed it to execute in late update I think? And, I wasn't too sure how to accomplish that.

terse pier
#

I just ended up using Animation Events as I am in a rush

#

makes my code messy but eh, I'll take it

latent latch
#

that's the spirit

kindred scaffold
#

Hey, dont know if this is the right channel, but TMP has completely broken on me, here are all the characters showing up wrong, and the errors

#

The font asset seems to be broken, im not sure how i would fix it though

placid summit
#

This one of the pains of Git, I had same issue. Use LFS or just use an easier source control system like SVN which I prefer ๐Ÿ˜ƒ

latent latch
#

or use the font asset creator thing

kindred scaffold
#

yup, i just recreated the atlas

#

happened while merging on git

chrome trail
#

So are marching cubes just for random mesh generation or are there ways to build specific shapes with it? I'm still not really understanding it or even if this is something I want to explore

hexed pecan
#

It's just often used with random/procedural generation, if it is used

chrome trail
hexed pecan
#

That's up to you - depends on your needs. If a regular terrain isn't enough and you need stuff like caves and overhangs then it is good

chrome trail
#

What I'm trying to do is have a character remove a semisphere shape from a mesh so as to dig a hole

hexed pecan
#

Yeah was about to say, if the mesh needs to be edited by the player then that is one of the advantages of marching cubes

#

Otherwise you could just 3D model the terrain

chrome trail
#

Because the way I have it set up right now is it just pushes the vertices around and that eventually reaches a point where I just can't dig any deeper because the vertices are too far apart from the player and one another

hexed pecan
#

Thats how 7 days to die does it, and a bunch of other games (astroneer?)

placid summit
#

The downside of marching cubes is you end up with very limited angles - it is still a bit boxy. Are you not limited to flat, vertical and 45 degree slopes?

hexed pecan
#

Think I remember seeing some implementations where the density grid is based on floats instead of bools, allowing for smoother transitions

#

That gets more complex though

chrome trail
hexed pecan
#

Good old Seb

chrome trail
#

Ok, so I think I'm getting the theory a little better. The idea is that the actual configurations are these isolines (or I guess isoplanes in the case of cubes rather than squares) that try to separate the corners of the cube that ARE turned on from the ones that AREN'T and these isoplanes become the mesh triangles you want to create. That sound about right?

#

From there I assume then that you assign each of these corners a float value between 0 and 1 to fine tune where you want the isoplane to place its point as it's otherwise going to place it in the middle between the two points

swift falcon
#
   [SerializeField] private float mouseSensitivity = 100.0f;
   [SerializeField] private Transform playerBody;

    private float xRotation = 0.0f;

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

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

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

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);
    }

Why does my camera movement stutter when I look up and down? But not left and right.

hexed pecan
#

And after you remove that, you need to make mouseSensitivity a lot smaller

swift falcon
#

oh alright

#

still does not feel really smooth tho compared to horizontal rotation

#

its like when it goes above 0 on x rotation it stutters when I look up and down

heady iris
#

are there any rigidbodies involved?

swift falcon
#

no

austere cape
#

I want to know what's the object that teleport when I teleport with the VR the exact object

heady iris
# swift falcon no

You can check if it's an input problem by replacing mouseY with a constant

#

like, say, 30

#

or maybe use 25 * Mathf.Sin(Time.time * 3) to make it go up and down

placid summit
#

Anyone know what makes UI Graphic component a registered collider with a canvas raycaster? I want a minimal collider without using that class on my UI, but for now I just use that and stop it drawing anything!

heady iris
#

so I'm just figuring this out myself (like, starting yesterday)

#

there is an interface called ICanvasRaycastFilter

#

if you implement it, it adds a method that the graphic raycaster calls

#

I think that method gets called as long as you're inside the bounds of the Graphic (which Image derives from)

placid summit
#

but if I only implement that then I get no collision - if I make it a Graphic I do

heady iris
#

it's a Graphic Raycaster!

#

i just realized that lmao

plucky inlet
#

Does anyone know, if you can check if a using System.Timers timer is running? reading through the docs right now, but maybe someone knows it already

#

Oh, I guess it might just be as easy as .Enabled

gray nebula
# lean sail whenever you get around to solving it

So I had a number of errors that my tired brain just couldn't compute.

First I had a list of the animation clips that I set to the anim override controller earlier in the script. This list became invalid once I removed the prefab from the scene to instantiat later.

Next I tried just pulling clips from the prefabs animator runtimeanimcontroller. Which would have worked, but I was calling the anim window update and then swapping my prefab to another model to preview. I just needed to call the anim window update after I swapped in my new prefab and then we were good to go.

Don't code while tired.. ๐Ÿ˜ช

magic harness
#

Hello guys, I could use some advice on my system design for Units.

I'm trying to implement an Unit with a state machine for controlling the macro state the unit is in(chasing, fleeing, roaming, etc..), and a command queue to deal with animations and concrete actions(moving, attacking, etc..). Also trying to enforce composition as much as i possibly can.

I already have some components, like a movement component, a health component which are all standard C# objects.

I already have the state machine and the command queue.

My commands are all scriptable objects and all units should be able to just reference them and call the functions passing themselves as arguments.

My big problem is actually checking and accessing these components from the unit argument inside their functions.

I tried adding a dictionary to my units like this

 public enum UnitComponents { Movement, Attack, Health, Mana, Loot}
    public Dictionary<UnitComponents, Object> components { get; private set; } = new Dictionary<UnitComponents, Object>();

but it does feel like just a band-aid in an otherwise pretty solid system.

Just creating variables in the Unit also doesnt seem too great, because not all units will have to move, or will need health...

this is my current movement command

    public IEnumerator Execute(Unit unit)
    {
        if (unit.components.ContainsKey(Unit.UnitComponents.Movement))
        {
            NavMeshMovementComponent unitMoveComp = (NavMeshMovementComponent)unit.components[Unit.UnitComponents.Movement];
            unitMoveComp.Move();
            unit.animator.CrossFade(moveHash, 0.1f);
            yield return new WaitWhile(unitMoveComp.HasReachedDestination);
            Logger.Log("Move Finished", this, LogType.CommandLog);
        }
       
    }

which is not working just yet because i cant convert from object.

latent latch
#

Wouldn't your enemy SO contain SOs of command units

#

If that's what you're aiming for. Such that you have range enemy AI and stuff

#

Otherwise the prefab route and populate an Enemy prefab with commands seems fine

somber vortex
#

got a strange situation... In my game I move position of objects at certain times during the game. When I run it in the unity editor this works fine but when I do a build the positions aren't updating. Any ideas?

magic harness
#

The difficult part is joining all of that togheter

leaden ice
#

msot of the time differences in build come from:

  • Execution order issues (script execution order is not guaranteed across platforms)
  • Framerate-dependent code
latent latch
#

If they are in low hp sub state/conditions then you should have a field on the SO for what unit should be checked when that state is entered

somber vortex
# leaden ice lots of things could be wrong. First thing to do is check the player log for er...

it's probably the frame rate dependent code. What I'm seeing in the editor is if I go frame by frame then the object updates to the new position I want for one frame... but then reverts back to it's original position which I don't want it to do thereafter. But if I just run it without stepping through frame by frame it seems to work (most of the time). But then when I build it it doesn't work at all

#

But I can't see in the code what is making it revert back to it's original position. It doesn't seem like there's anything telling it to do that

leaden ice
somber vortex
#

I will share it. Just finishing another issue then will share

#

how do you paste it in? I think someone sent a link before so the format looks right

leaden ice
#

!code

tawny elkBOT
leaden ice
#

Ideally use a paste site

somber vortex
#

ok will do this shortly

#

ok ready to do this... Shall I just paste the whole script? it's around 130lines... @leaden ice

leaden ice
#

That's tiny

#

yes the whole script

#

Use a paste site

somber vortex
#

ok cool I'll paste it. One sec

#

will do

#

is that ok?

somber vortex
#

ah wait it didn't paste the whole thing

dusk apex
#

A paste site

wispy badge
#

same problem guys, does anyone know how to solve this?

somber vortex
#

ok one sec

plucky inlet
somber vortex
#

I don't get it.... sorry haha never tried this before

#

I used the paste.ofcode site

#

it pasted it to a webpage

#

how do I get it from there to here in the correct format?

#

ohhhh right

wispy badge
somber vortex
#

is that link working?

heady iris
#

an HMAC is used to produce a digest of data with a secret key

#

Does the error provide any more information?

somber vortex
#

okay so the line I'm having trouble with is line 123. Where I take an object from the list objs and position it in a new position. It positions it in the new position for one frame and then reverts back to it's original position. I can't see what is making it revert back to it's original position though

plucky inlet
heady iris
#

it should reject the certificate if it isn't trusted, but I would expect an error about the lack of trust

somber vortex
#

I can explain more what the code is trying to do if that helps

hexed pecan
heady iris
#

looking at the source code, it looks like the code only supports SHA1

#

goofy

#

SHA1 is busted, and it's probably no longer the default used by openssl et al.

somber vortex
#

the controller script it using rigidbody.velocity etc. When I comment out all of the code on rigidbody movement then the repositioning works correctly

heady iris
#

which is bad, because SHA1 is bad (relatively)

wispy badge
wispy badge
#

Thanks bro @heady iris

hexed pecan
somber vortex
#

ok one second...

somber vortex
#

when I comment out the section 'public void FixedUpdateShark1()' then the repositioning in the other scripts works

#

I'm just testing it again now to make sure

#

ok so it's 100% the 'public void FixedUpdateShark1()' section in the controller script causing the issue. I just did a build with that section commented out and all of the repositioning works perfectly. As soon as I have that section running in the code then the shark moves to the new position for one frame... but then reverts back to it's original position after which I don't want it to do

#

but I don't get how... I'm only updating the rigidbody velocity in the 'public void FixedUpdateShark1()' section. I'm not updating it's position....

plucky inlet
heady iris
#

Do you have "Interpolate" enabled on the rigidbody?

#

If so, setting the position of the transform will not work. The rigidbody will update the transform's position and rotation every frame.

#

You need to set the position of the rigidbody directly.

#

(if Interpolate is off, then the rigidbody only updates the transform in each fixed update cycle, and it synchronizes transforms before that happens, afaik)

somber vortex
#

yeah I do have interpolate on the rigidbody...

#

ah is this rigidbody.MovePosition?

heady iris
#

setting the position doesn't try to interpolate (so you won't see a few frames of the rigidbody flying across the screen)

heady iris
somber vortex
heady iris
#

ya, it's not something that'si mmediately obvious

#

Why do they not need a rigidbody?

#

Did you only add one because you need collision messages?

somber vortex
#

yeah... and the player itself has a rigidbody

#

only one of the two objects need a rigidbody right

#

for collisions to work

heady iris
#

A non-kinematic rigidbody can hit static colliders, as well as another kinematic rigidbody

#

It would be reasonable to use a kinematic rigidbody (with Interpolate off) and to just set the position every frame

somber vortex
#

Can I use rigidbody.MovePosition as a workaround in the meantime?

heady iris
#

both calling MovePosition and setting position won't actually do anything until the next physics update

#

so keep that in mind

#

What you can also do is call Physics.SyncTransforms() immediately after modifying the shark's position

#

I think that will get it to teleport properly (and immediately)

#

but I'm not sure on that

somber vortex
#

I'll try that

plucky inlet
#

I think MovePosition in fixedupdate is taking interpolation into account

somber vortex
#

I'm going to try a few things in next few minutes to see if I can get it working for the time being

plucky inlet
#

From docs, only setting the position of rigidbody directly will teleport

heady iris
#

I need to refresh myself on the exact differences (I keep forgetting how each way interacts with other rigidbodies that get in the way)

plucky inlet
#

Same ๐Ÿ˜„ thats why I am just relaying the doc info here ๐Ÿ™‚

somber vortex
#

you're completely right on the interpolate thing! As soon as I turn it off everything works. Now to just try to get it to work with the interpolate for the timebeing as I need interpolate on to keep the rigidbody rotations looking smooth

hexed pecan
somber vortex
#

you guys are awesome! Thanks so much! I spent most of my day trying to figure this out and was getting nowhere. Didn't even do any work in my actual job today because of this lol. Released a game on steam this morning and this was causing big issues so now can update it with the fix. Thanks all!

thick meadow
#

Hey, guys. I'm new to unity, I need a little help with one question. I'm using the OnPointerEnter method to change the sprite when the player hovers over it:
public void OnPointerEnter(PointerEventData eventData)
{
transform.localScale = originalScale * scaleFactor;
}
but my sprites are not square, and this method does not work with Polygon Collider and it turns out that the sprite shrinks when the cursor touches the invisible area around the sprite. The only thing I've come up with is to check in the Update method for each item to see if the cursor coordinates match the Polygon Collider coordinates, but I think this is obviously not the best solution, is there any way to fix this, thanks for your help in advance.

leaden ice
#

And what kind of object is this

thick meadow
#

UI.Image

plucky inlet
#

So you could set this to a desired value to avoid the hit test on invisible areas

rigid island
#

Why it's not exposed in inspector is beyond me UnityChanLOL

plucky inlet
#

the more you expose, the more possiblities for missing setting a value you create

leaden ice
# thick meadow UI.Image

UI elements should not have colliders. Colliders are for world space objects.
So - what are you trying to do again?

rigid island
naive swallow
plucky inlet
#

Also your image needs to be set to read/write. Even more possibilities to make it not work

vagrant agate
#

but .. but... when things don't work its fun to fix.

austere solar
#

bruh, im tryna code in Unity, but VSC doesn't show me available classes and hints (without them i'm lost) and VS can't open the project

#

what do yall code in?

tawny elkBOT
knotty sun
austere solar
knotty sun
#

the .csproj files not the .cs files. Please read what I write

austere solar
#

ah. Theres a diff. Right, my bad

thick meadow
# leaden ice UI elements should not have colliders. Colliders are for world space objects. So...

I have an array of objects they should be arranged in the form of several tabs I used for this GridLayoutGroup and Panel and then took sprites one by one from the list and displayed them on the screen assigning their value to the prefab Image, and for these objects I just wanted to make animation on mouse-over and also the ability to create a copy of them and move it, something like an infinite source of resources in the game.

leaden ice
#

for creating copies - I guess you mean dragging and dropping? That is well-trod ground where you can find lots of tutorials. I think the best thing though is to use e.g. Graphics.DrawTexture while dragging until you drop it somewhere

thick meadow
heady iris
#

Button doesn't render anything

#

You use it alongside a graphic.

leaden ice
#

Selectable also works, instead of Button

#

Button is just a Selectable with an onClick event

turbid spade
#

Hi guys I had an issue with the job system

I have 2 functions that get triggered through buttons

thick meadow
#

Thank you so much, sorry for possibly stupid questions

turbid spade
#

is that normal?

#

Inside the job I call an api that returns an http stream

#

the other function is a regular http response

leaden ice
#

oh unity job system?

#

Unity jobs are not meant to run infinitely. They're meant to be pretty short lived

#

Also - jobs can't deal with managed objects which are present in almost any HTTP framework

#

It would be very unusual to make HTTP requests within a job

knotty sun
austere solar
knotty sun
#

thats fine, now the complete VS window with the solution explorer open

austere solar
#

Ok the diff is that now it opened the file, but the classes are still not loaded - they're not green. And the project is unbrowsable.

knotty sun
#

!code

tawny elkBOT
lapis cairn
#

sorry

knotty sun
#

use a paste site

lapis cairn
#

the game i am making is like slender 5 pages spawn around the map I wanna make a mode where you see how long you can last I want a page to spawn if one is collected how do I make this code do this?: https://hastebin.com/share/awewuxicom.csharp

austere solar
knotty sun
vagrant agate
heady iris
tawny elkBOT
austere solar
rigid island
#

In Solution Explorer window

#

where it says "Assembly Csharp"

simple egret
austere solar
austere solar
#

ok now i have a new problem - can't figure out how to make something that can play a menu song indefinitelly. However, i have an ITIN part and a LOOP part of the song. I wanna make the script make the INIT part play first and than when its done loop the LOOP part.

I have a code that does it, but it either does it late

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

    audioSource.loop = false;
    audioSource.clip = track1;
    audioSource.Play();
}

// Update is called once per frame
void Update()
{
    if (!audioSource.isPlaying) 
    {
        audioSource.loop = true;
        audioSource.clip = track2;
        audioSource.Play();
    }
}

Or early

// Start is called before the first frame update
void Start()
{
    Run();
}

// Update is called once per frame
void Update()
{
    
}

private async void Run()
{
    audioSource = GetComponent<AudioSource>();

    audioSource.loop = false;
    audioSource.clip = track1;
    audioSource.Play();

    await Task.Delay((int)Math.Floor(track1.length * 1000));

    audioSource.loop = true;
    audioSource.clip = track2;
    audioSource.Play();
}
vivid halo
#

Are there any resources or rules of thumb for architecting my code if I want to leave the option open to implement co-op multiplayer in the future?

leaden ice
#

Don't use singletons for the stuff relating to a player.

rigid island
simple egret
#

Because there's an await in it

#

Valid alternative to a coroutine

rigid island
#

wouldn't it be better to just check the current time /timeleft on audiosource, in update to switch to next one ?

simple egret
#

That's what their first solution is doing

rigid island
#

its using isPlaying

simple egret
latent latch
#

audio mixer would be good for this

austere solar
#

propably. Just heard that the loop lags the audio too ๐Ÿ˜ญ

#

tho im a beginer so idk what that is lol