#archived-code-general

1 messages ยท Page 47 of 1

deep willow
#

i added a return type to a method, and im calling that method with a UI button, but it says the return type is not compatible. how do i fix this?

quartz folio
#

make a method without a return type

deep willow
#

I kind of need the return

quartz folio
#

The button cannot use it, so no

#

Make another method that calls the one that has the return, and doesn't return it

deep willow
#

Ah that worked thx

leaden mural
#

How can I use something in a Unity scene as a reference for a prefab? So like, I need to reference my script where the int points is, but I need to set it to an instance of an object, but the editor won't let me.

quartz folio
tired dagger
#

hi all

#

Flash question, Just updated my Visual Studio 2022 then this happen. The simpleJSON shown a error and all related to JSON. Plse help me

prime sinew
leaden mural
tired dagger
ionic socket
#

does &= exit early if the left-hand side is already false?

polar marten
somber nacelle
#

& doesn't short circuit though, it evaluates both sides every time. it's && that short circuits

ionic socket
#

so &&=?

polar marten
#

"Did you mean &&="

ionic socket
#

if I want to avoid the RHS evaluation

polar marten
#

that would seem that &= is correct

#

based on this valuable research by vertx

ionic socket
#

cool

polar marten
#

i meant x && y i am tired ๐Ÿ˜ฆ

quartz folio
#

I am unsure if it will always compile that way and bypass the check; you would have to check the decompiled results of what you've written.
For example changing the code I used to:

bool a = new Random().Next() == 0;
a &= new Random().Next() == 0;

results in &=, which is unclear to me, and I can't read IL reasonably

somber nacelle
#

fun fact about sharplab if you didn't know, you can hover over the IL and it tells you what it is doing. from what i can tell it's doing basically the same thing for each. the only difference seems to be when it is loading the variables on the stack

quartz folio
#

I know I can hover, I still can't read it well enough to be able to compare

#

The previous example was just an interesting note that it all compiles to the same thing if the arguments have previously been evaluated (which may or may not change if it wasn't compiled in Debug mode)

spark helm
#

Hey does anyone know if theres a way to Have 1 state in an animator layer that doesnt inherit the avatar mask of the layer?

spark helm
#

ah sorry i just thought it would only be possible in script

hexed pecan
#

Pretty sure that if it's possible, its done in the animator window. But I suspect it's not possible

#

In any case, even if it ends up being code related, people in the anim channel would know better

vestal crest
#

i have navmeshsurfaces in a level and i buildnavmesh at awake. when i see it in navigation tab navmesh seems fine but agent cant calculate path?

#

any ideas why its not working

#

it worked when i change collected object to all in navmeshsurface component

hexed pecan
vestal crest
#

yes my level generated at start

#

i have different levels thats why i instantiate them

quartz folio
#

What language is this?

pearl whale
#

I got the wrong discord, it's lua ๐Ÿ˜…

quartz folio
#

Looks like Roblox. This is a Unity server, you're in the wrong place

pearl whale
#

sorry

dense herald
#

Hi! What's something you could use as an alternative to OnTriggerEnter2D? It doesn't work with 0 timescale and I've tried Physics.OverlapBox but that doesn't seem to work either for some reason.

leaden ice
dense herald
#

Okay thanks.

wicked wagon
#

I think it's not really coding related but any ideas what's causing this? When moving the player it randomly skips frames(?) and player is somewhere else

leaden ice
tacit kestrel
#

looks like it's position is getting reset

median folio
#

Hello, this is driving me crazy as I've done this many times before.

I have an object, when I drop it anywhere on the screen I want it to tween to a position (using DoTween). I was using startpos from another class to do this but noticed an issue where it would snap back to where my mouse was last positioned.

To try and simply this, I hard coded a value in but still get this weird issue where it moves back to my mouse position despite the hard coded value.

I then tried to use a simple transform.position which worked without issue - my object always moves to that position.

Any idea why DoJump moves to the correct position but then seems to move again afterwards?

 var startpos = new Vector3(23f, -0.26f, -107f);
 transform.DOJump(startpos,5f, 1, 1f).SetEase(Ease.OutQuad);
 //transform.position = startpos;
wicked wagon
#

I think it's not happening when vsync is on too

#

I'll try to solve it

leaden ice
#

Or CharacterController?

median folio
#

@leaden ice I actually didn't use either but even after adding a rigidbody the issue is still there.

Also worth noting I just tested again and it worked 9/10 times before failing to stay at that hard coded position so its pretty inconsistent at the moment

leaden ice
#

Anyway you'd have to show more code then

#

Presumably you have other code changing the position

#

(or some other component like mentioned)

dim furnace
#

How did my game go from this in the editor to this in game

somber nacelle
dim furnace
#

ok

median folio
#

@leaden ice Got it, I was putting together some sample code to share and found the issue. I was setting the drop state twice so it was causing the code to re-trigger

#

I forgot that code was related when I was doing my debugging

jagged laurel
#

by the way, what is the best way to register an account on the unity, I just chose a google account

vagrant blade
#

Not a coding question. The best way is one you'll remember.

severe maple
#

Can someone give me a pointer on how to get the health bars (slider bars in world canvases, children of each unit) to sit in front of the current unit but not overlap units in front? Tried messing with render queue in shader but seems to not do anything

wicked wagon
mental rover
distant owl
#

does anyone know how to change properties of an object that has been picked up by ontriggerenter

wicked wagon
mental rover
#

it's an interesting observation but I'd probably not assume that's the case until you're able to narrow it down further

hexed pecan
distant owl
hexed pecan
distant owl
#

oh wait im pretty sure I have to use get component

distant owl
hexed pecan
#

Mesh collider or mesh renderer? (you said both)

distant owl
#

oh sorry i meant mesh renderer

hexed pecan
#

Yep then use col.GetComponent<MeshRenderer>()

#

Or TryGetComponent so it does a null check basically

distant owl
#

oh okay yeah i thought it would be something like this thank you

#

so if i were to turn it on or off i can just put that in the brackets?

#

nope thats not it

#

oh no I do GetComponent<MeshRenderer>().enabled = false;

#

okay that seems to work thank you for the help @hexed pecan

dense herald
#

Simple question, what's a variable type that doesn't show in the inspector but can be accessed from all scripts?

hexed pecan
dense herald
#

With public private and whatnot basically

hexed pecan
dense herald
#

Ohhh

hexed pecan
#

Sounds like you want static

dense herald
#

Okay thanks

fiery hound
#

Hi guys does anyone know by any chance where can I look into how-to cache images from unitywebrequest?

thin hollow
#

Is it possible to add a function to an enum, or conversion rule? What I want:

public enum EFoe {Friend,Foe}

class Something
{
  private EFoe state = EFoe.Friend

  void DoSomething()
  {
    if(state.IsFriend)
      {
          //DoStuff
      }
  }
}

RN the best I could come up with is creating a wrapper, it works I guess but it is relatively bulky (more stuff to type out):

public enum EFoe {Friend,Foe}
public static class IsFoe { [MethodImpl(CMath.INLINE)]  public static bool Bool(EFoe p) => p == EFoe.Foe; }

class Something
{
  private EFoe state = EFoe.Friend

  void DoSomething()
  {
    if(!IsFoe.Bool(state))
      {
          //DoStuff
      }
  }
}

Is there a better way?

oblique spear
#

Is there a way to debug the raycasthitpoint visually? Like debug.drawRay but instead of a line just a big ball for the hitpoint?

thin hollow
# oblique spear Is there a way to debug the raycasthitpoint visually? Like debug.drawRay but ins...

I've written myself a function for something similar:

    /// <summary>
    /// Trace line as bool
    /// </summary>
    public static bool TraceLine(Ray ray, float distance, int layerMask, QueryTriggerInteraction ignore=QueryTriggerInteraction.Ignore,bool debugDraw = false, Color? clr = null,  float drawtime=0)
    {
        RaycastHit hit = TraceLineRC(ray, distance, layerMask, ignore, debugDraw,clr,drawtime);
        return hit.transform != null;
    }
    /// <summary>
    /// Trace line and return hit
    /// </summary>
    public static RaycastHit TraceLineRC(Ray ray, float distance, int layerMask, QueryTriggerInteraction ignore=QueryTriggerInteraction.Ignore,bool debugDraw = false, Color? clr = null,  float drawtime=0)
    {
        RaycastHit hit = default;
        bool result = Physics.Linecast(ray.origin,ray.origin+ (ray.direction * distance), out hit, layerMask, ignore);
        
#if UNITY_EDITOR
        if(debugDraw)
        {
            float time = drawtime;
            if(time <Time.deltaTime)
                time = Time.fixedTime / 600;
            Color devColor = Color.green;
            if (clr != null)
                devColor = (Color) clr;
            
            DebugWireSphere(ray.origin, devColor, 0.01f, time);


            if (result)
            {
                Debug.DrawLine(ray.origin, hit.point, devColor, time);
                Debug.DrawLine(hit.point, ray.origin + (ray.direction * distance), Color.red, time);
            }

            else
            {
                Debug.DrawLine(ray.origin, ray.origin + ray.direction * distance, devColor, time);
            }
        }  
#endif
        
        if (!result)
            hit = default;
        return hit;
    }
oblique spear
oblique spear
static matrix
#

does Physics2D.Linecast Automatically hit triggers or do I have to turn that on

somber nacelle
#

depends on the queries hit trigger setting in the Physics2D settings

static matrix
#

ahh

#

ok

spark vine
#
UnityEngine.Mesh.CombineMeshes (UnityEngine.CombineInstance[] combine) (at <7b2a272e51214e2f91bbc4fb4f28eff8>:0)``` is there any way around this? The `CombineMeshes` function is quite useful for what I'm doing, but I don't see any way of specifying the integer format of the index buffers
jagged laurel
#

By the way, I also wanted to ask I didnโ€™t notice in my personal data

#

I'm about Timezone

west sparrow
spark vine
#

yep, figured it out in the link after my post

hidden kindle
#

When should I use jobs?

#

I want to use it, but I feel like it's a lot of boilerplate code

steep drift
#

If you have processing to do which benefits from threading.

#

IE can run for a while without holding up everything, can't be completed in a frame, and can't meaningfully be sliced.

small void
#

Does anyone know of a good method/design pattern for creating a singular UnitAnimator script that can trigger different animations based off a wide list of ability's that different units could have. I dont want to have to go in and hardcode the strings for each ability. Is there a way to store the animation in the ability data and trigger it through code?

vagrant oasis
#

how i can change this code to a code with overlap sphere that sets ui position to the object that have a "interactable" script that is the nearest to the ray point???

        RaycastHit hit = RaycastPlayer();
        if (hit.transform != null)
        {
            //Hit something
            GameObject hitObject = hit.transform.gameObject;
            Interactable interactable;
            
            if (hitObject.TryGetComponent<Interactable>(out interactable))
            {
                Vector3 UIPos = playerCameraInstance.WorldToScreenPoint(hitObject.transform.position + Vector3.up * yOffsetInteraction);
                interactionUI.position = UIPos;
            }
        }
hot yacht
hot yacht
# vagrant oasis how i can change this code to a code with overlap sphere that sets ui position t...

i don't knonw but, i was thinking you can store each hit point that have interacble and then search with sqrMagintude or Vector3.Distance.
so every object that overlap with sphere, add to a list/array/anything and then loop them

foreach(GameObject myinteractable in intracbles)
{
  var testing = myinteractable.GetComponent<intracbles>();
  // check nearest
  // do something. 
}

i don't know if this will help...

glacial crystal
cobalt flint
#

Good morning community. I'm struggling with an issue regarding scaling a prefab instance during runtime. The code works, but the instance does nothing in the game scene. Local scale shows as updating but I believe it still holds the overriding local scale of the prefab. Any advice?

scenic creek
#

Make sure it's not static.

#

Like the gameobject is not marked static in the editor

cobalt flint
#

The instance is not static, however the prefab is.

#

I will test.

cobalt flint
swift falcon
#

Does anyone know why i cant set animation curves in bulk inside UnityEngine, But the UnityEditor.AnimationUtility has a bulk method called AnimationUtility.SetAnimationCurves

#

:\

#

cant use it on runtime, my animations are all generated on runtime

#

is there any way i can pull in unityeditor ref on my build?

#

the Animation itself has animation.SetCurve but this isn't a bulk

#

nor can you get animation curves on runtime without accessing unityeditor

#

I cant serialize animations then load them cus theres too many combinations...

#

๐Ÿคฏ

#

    float horizontal;
    float vertical;
    public float speed = 10;
    void Start()
    {
        GameObject.GetComponent<Rigidbody2D>();
        GameObject.transform.position = Vector3.zero;  
    } 
    void Update()
    {
        horizontal = Input.GetAxis("horizontal");
        vertical = Input.GetAxis("Vertical");
        
        gameObject.transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
    }
#

Hi I'am trig to make an object move constantly to the right, but for some reason it doesn't work, can someone help me?

swift falcon
#

Then when you use Update() you use gameObject with lowercase

#

it suppose to set the ship to the 0,0,0 position

#

No that code wont even compile

#

Not too sure maybe you left code out?

#

the rigidbody it's for something else, doesn't matter

#

so what should I do?

hexed pecan
#

Post the code that compiles

#

Make sure that speed isnt 0 in the inspector

swift falcon
#
public class PlaneMovement : MonoBehaviour
{
    Rigidbody2D rb;
    GameObject GameObject;
    

    float horizontal;
    float vertical;
    public float speed = 10;


    // Start is called before the first frame update
    void Start()
    {   
        GameObject.GetComponent<Rigidbody2D>();

        GameObject.transform.position = Vector3.zero;
        
        
    }   

    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxis("Horizontal");
        vertical = Input.GetAxis("Vertical");
        
        gameObject.transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
        
        PMove();

    }


    void PMove()
    {
        transform.rotation = Quaternion.Euler(0, 0, rb.velocity.y * 2);
        
        if (vertical > 0 || Input.GetMouseButtonDown(0))
        {
            rb.gravityScale = -4.314969f;
        }
        else rb.gravityScale = 4.314969f;
    }
}
#

Nvm

#

use

GameObject.transform.position += new Vector3(speed * Time.deltaTime, 0, 0);

hexed pecan
#

That doesnt compile either

#

Oh.

swift falcon
#

You can see a ref here GameObject GameObject;

#

But its not set

hexed pecan
#

A variable named GameObject...

swift falcon
#

Subzero its not too clear what object your trying to move lol

hexed pecan
swift falcon
#

You have a GameObject ref inside ur code, you are moving the gameObject of the script

#

would you like to move the rigidbody?

#

I want to move the object associated to the script

#

can you take a picture of your script attached to the object

#

e.g. mine

#

hmm seems speed is fine

#

no clue it should work lol

#

thanks I solve it, it was the blue GameObject variable

#

You might want to remove this dead code

#

        GameObject.GetComponent<Rigidbody2D>();

        GameObject.transform.position = Vector3.zero;

#

It does nothing

#

Your GameObject variable is never set, im suprised you dont end up with a null pointer exception

#

I don't know why I put it in there

#

jajajaja

#

thank you so muchuwu

#

np ๐Ÿ˜›

crude marten
#

i have a door script that can open and close my doors pretty nicely but the issue is if you spam the door open button the door starts bugging out and throwing 360s on me so i was wondering if there is a way to check what the animator is currently playing so i can make so if the door is in the middle of opening or closing you cant use it. here is my code i dont think it matters but i put it here anyway just in case

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

public class Door : MonoBehaviour
{
    public bool DoorUsed = false;
    public bool DoorOpen = false;
    public Animator OpenClose;


    // Start is called before the first frame update
    public void Start()
    {
        OpenClose.Play("Closed");
    }

    // Update is called once per frame
    void Update()
    {
        if(!DoorOpen && DoorUsed)
        {
            OpenClose.Play("Close");
            DoorUsed = false;
        }
        if(DoorOpen && DoorUsed)
        {
            OpenClose.Play("Open");
            DoorUsed = false;
        }
        
    }
}
hexed pecan
#

Transitions with has exit time enabled

swift falcon
#

if you want it on a specific frame, i think theres a few events onAnimationstart

#

and end

#

Although not sure why you'd handle door animations using the update function and a boolean

swift falcon
#

What you can do is have a method to Open and Close the door.

private boolean _opened;

public void ToggleDoorState(bool open) {
    _opened = open;
    OpenClose.Play(_opened ? "Open" : "Close");
}
#

No update method and boolean check required every tick

#

to Open the door you'd do:

door.ToggleDoorState(true); to close it you'd do door.ToggleDoorState(false);

crude marten
#

what does _opened mean

swift falcon
#

if the door is opened already (default false)

#

its a boolean

#

You use "doorUsed" and "doorOpen"

#

When you only require a single boolean to denote a doors state

#

you can even get more smart with it and use doors.Toggle();

which would do:

public void Toggle() {
     ToggleDoorState(!opened);
}

If the door is open it will close it
If the door is closed it will open it

spark yew
#

okay so like

#

i'm using a very ancient version of unity

#

and i can't seem to access "unityscript.lang"

swift falcon
#

Sad i cant use unityeditor lib inside build

#

blocker

#

:[ inb4 i have to use the cloud to make the animation with unityeditor lib

#

and ondemand feed it into the game client

hexed pecan
spark yew
#

i asked here just in case

hexed pecan
hexed pecan
crude marten
#

if it is even possible

crude marten
tawny mountain
#

Is there a way to count how many a character appears in a json text file? I'm looking online and there's similar questions with answers in the form of code , I was maybe looking for a text editor that could do it

#

example
if I wanted to count a remove all but 1 "a" in the following json imgae

polar marten
#

what is the unity idea here

ionic socket
#

Question about using interfaces - imagine an old school JRPG like FF2 or Dragon Quest. The player has spells, some which can be used in combat (say, Fire) and others than can be used on the Overland Map (Teleport), and some that can be used in both, for eg Heal. Using interfaces, like ICombatSpell, IMapSpell seems like it'd be appropriate because spells in each context would require distinct data (ie, combat spells have a target), but that leads to having to make a concrete class for each combination of interfaces you want, whereas most of us would conceptualize when you can cast a spell as a property of a spell - you'd check a boolean for "isCombatSpell" or "isMapSpell" or maybe something more in depth.

What is the traditional approach to this issue?

regal marsh
cold parrot
# ionic socket Question about using interfaces - imagine an old school JRPG like FF2 or Dragon ...

the traditional (stupid) approach is to use the full force of OOP, multi inheritance and a godly master baseclass. luckily in unity you don't have to do that, and its also not the 90s anymore so you use components and forget about interfaces... if you plan on using a dependency injection container or some other sort of system that you build outside monobehaviours go for interfaces and IoC. Generally you'd make small interfaces that express and Aspect/Capability of something, e.g. ICastable, ICollectable, IDamageable, and compose these in whatever way you like on the implementation side.

ionic socket
regal marsh
#

but the zombie just isn't walking that path

#

lemme grab the code

cold parrot
# ionic socket so basically just roll with making a concrete class for each combination of inte...

as i said, you can compose that on the implementation side whichever way you like (thats the whole point of interfaces, they do not imply any specifics on the impl side, unless you make leaky abstractions), classes implementing multiple interfaces or just a GameObject with a bunch of components implementing each one separately and all called from some sort of "engine" that ties the whole thing together

ionic socket
polar marten
cold parrot
#

a leaky abstraction is when your interface makes assumption about how the outside world is constructed/behaving

polar marten
#

since you have a limited number of spells keep it constrained

polar marten
#

that means you would have your GameSpells class, and allow it to grow organically

fiery path
#

Random question about scripting.
I have to explain a script within a word document.
Would the best approach be to do this:
Paste the script
Explain it fully in Psuedocode
Then explain more precise details after

ionic socket
polar marten
#

and add the bits and pieces you need to implement the spell in the right places. instead of interfaces, think about how repeating behavior can be a function you call in multiple places, rather than an interface you expect on a component

polar marten
polar marten
#

so to express a combat behavior as a sequence of these actions... write a method that does the actions.

#

don't try to program inside the inspector

ionic socket
#

oh yeah this is very much not inspector or game-object driven. but I want to like, check if the incoming damage implements ILightningDamage if the player is standing in water or whatever, but I don't want to create a damagetype class for my omega weapon that implements ILightningDamage and IFireDamage and IEarthDamage etc etc. I would do more of a "tag" system but I do want to enforce some contracts on these types, like if it's IMultiTarget, I should be able to access IEnumerable<enemies> Targets or whatever.

polar marten
# ionic socket LISPs?

for example.

public class Actions {
 // returns the actual amount of damage dealt
 protected int DealDamage(int damage, Character target) {
   ...
 }
 // returns summoned character or null
 protected Character Summon(BaseCharacter baseCharacter, int position) {
   ...
 }
 ...
 // used by: Necromancer, Lich King enemies
 // Deal {damage} damage. For each target that dies, summon a {character}.
 async UniTask Fireball(int damage, BaseCharacter baseCharacter, List<Character> targets) {
  foreach (var target in targets) {
   DealDamage(damage, target);
  }
  var died = await GameManager.instance.currentGame.EndOfSequence();
  foreach (var didDie in died) {
   var position = didDid.position;
   Summon(baseCharacter, position);
  }
 }
 ...
}
cold parrot
stark kindle
#

Hello guys, I'm currently working on a parkour system, I'm currently working on walking on railing feature but I'm having trouble figuring out how to do it. Can someone give me a solution? Thanks

polar marten
pine spire
#

I would probably just do an array of damage types in case like this

polar marten
#
public class Actions {
 // returns the actual amount of damage dealt
 protected static int DealDamage(int damage, Character target, DamageType damageType=DamageType.Physical) {
  ...
  // check for immunity 
  if (target.attributes.immunity.Contains(damageType)) {
   damage = 0;
  }
  ...
 }
...
 ...
 protected static void GrantImmunityTo(DamageType damage, Character target)
 {
  ...
 }
}

@ionic socket

#

also, observe that with this approach, you can progressively add functionality

#

this is what i mean by strongly coupled

#

you do not need to add a trait to the fireball and water canon spells

#

via an interface

#

in their specific function implementation,s they will just call DealDamage with damageType set to whatever

#

you don't want DealDamage to inspect the class of its caller

#

it should basically be stateless

ionic socket
polar marten
#

i modified the methods to be static to emphasize the point

#

it's called "gameplay attribute system" because you wind up writing a ton of these

#

and they don't really exist on classes

#

they are just a dump of data inside a dictionary (i.e. attributes)

#

in this particular case attributes can be something like

ionic socket
#

I think this is similar to what I meant by a Tag system. and I suppose the tags themselves can be arbitrary data containers and will emulate (for my purposes) the utility of Interfaces. Like a single vs multi target attack could have a SingleTarget "tag" which itself is a class that just stores a target; whereas MultiTarget stores an enumerable.

polar marten
#
class Attributes {
 DamageType[] immunity;

 // get by name
 object this[string name] {
  switch (name) {
   case nameof(immunity):
    return immunity;
   ...
  }
 }
}

or

class Attributes : IDictionary<Attribute, object> {
 DamageType[] immunity;
 override object this[Attribute attribute] {
  switch (attribute) {
   case Attribute.Immunity:
    return immunity;
  }
 }
 ...
}
polar marten
#

the "attributes" container of this system should hold immutable primitives and be easy to copy, since you will be copying it a bajillion times

#

you don't want to store weird shit like polymorphic classes inside of it

ionic socket
#

haha yeah. I can sometimes get caught in the abstraction k-hole.

polar marten
#

you will want int GetValue(Attribute attribute), assuming the caller knows it will be an int. store everything inside a property OR a dictoinary. you can also access the properties semantically, like i whosed in my example

#

for the sake of readability

#

you can also mark these properties as virtual and do not declare IDictionary

#

if you want to be safer

main token
#

is there a good way of going about customizable keybinds? From what I can gather the easiest way is getting a KeyCode from string, but that seems rather janky to me

polar marten
#
interface IReadOnlyAttributes {
 IReadOnlyList<DamageType> immunity { get; }
}

class Attributes : IReadOnlyAttributes {
 public override IList<DamageType> immunity { get; set; }
   = new List<DamageType>();
}
#

@ionic socket in my experience, decisions like these are much more impactful for correctness

main token
# stark kindle ?

that's really vague, we are gonna need more information to work with

hollow stone
#

What's a good approach using interfaces on components? Considering that you may want to create dependencies in inspector and so on?
https://pastebin.com/p29ts8Bf Is there some better way than doing something like this?

polar marten
#
class Character {
 Attributes m_Attributes = new();
 public IReadOnlyAttributes attributes => m_Attributes;
 public Attributes mutableAttributes => m_Attributes;
 public Attributes GetAttributes() => m_Attributes.Copy();
}
regal marsh
ionic socket
regal marsh
#

That makes sense. How would you recommend I fix it?

regal marsh
#

Sorry I donโ€™t know a whole lot about navmeshes

main token
#

that should allow to only be able to walk on a certain layer

#

I'm sure there are better solutions, but that's what I can come up with on the spot

potent sleet
#

boxcasting probably

stark kindle
potent sleet
#

check each side of the character

stark kindle
#

i'll try both and see which one works better

#

thanks guys

regal marsh
ionic socket
regal marsh
fringe ridge
#

Any ideas? running on mobile web browser

ionic socket
#

the intended behavior is that the zombie should turn and move towards their target just like the gizmo does?

regal marsh
#

yes the zombie should target the car more accurately than it does now

ionic socket
#

_contactTimer might be too high, it looks like that prevents the zombie from choosing a new target?

regal marsh
#

i think contact timer is for attacking the player. let me double check for you though.

#

oh actually

#

you know that may be a good point

hollow stone
regal marsh
#

it's not explicitly tied to pathfinding, but the pathfinding function will call cancelmove if they have to wait before they can hit the car again, which doesn't affect turning or the ability to accurately track the player from what i can tell

topaz plaza
#
        public void Open(int index, string menuName)
        {
            var menu = Instantiate(interactionMenuTemplate);
            menu.transform.GetComponent<Canvas>().enabled = true;
            menu.SetMenuTitle(menuName);
            menu.SetOnCloseAction(() =>
            {
                Destroy(menu);
                _menus.Remove(menu);
            });
            _menus.Insert(index, menu);
        }

For some reason I can not Destroy those prefab instances I created within an event callback.

As you can see in the screenshot the InteractionMenu(Clone) keeps stacking up.

I also tried DestroyImmediate just to be sure destroying does work at all

wintry stone
#

how could you go about rotating a transform over time?
I have this line player.rotation = Quaternion.Slerp(currentRotation, targetRotation, Time.deltaTime * rotationSpeed); but its super clunky

trim ferry
#

Hey guys i have this problem for a while now, basically i have this model that i want to make it follow me, the animations plays all good, perfect, but it doesnt move, i was suspecting it is the code, i want to make sure it is correct.

The script: https://hatebin.com/paywqfmwyo

trim ferry
#

lemme check

#

still nothing

#

it doesnt follow me

cosmic rain
#

Are there any errors in the console?

trim ferry
#

oops

#

sended 2

trim ferry
#

i had this problem before, but i dont know how i fixed it

clever spade
#

turn your animator off and try again

#

don't remove it just disable the script

trim ferry
#

oh

#

now it worked

#

why does the animator have relation??

clever spade
#

Your animator is constantly overwriting the transform.position

trim ferry
#

then how do i fix that

clever spade
#

Make the nav mesh agent a parent of the animated object

cosmic rain
#

Animator shouldn't move the root of the character. It should only animate bones.

trim ferry
#

k

#

ohh

#

i get it now, The object that contains the NavMeshAgent is trying to move, but the FollowingPlayer animation is on a specific position and it cant move because it is on that position still, because that is where i animated it, right?

clever spade
#

Correct

trim ferry
#

so i have to create a gameobject with the navmeshagent that will be the parent of the old navmeshagent?

clever spade
#

Either that or the very complicated task of not using animations that conflict with transforms

#

that includes rotations

#

The former is a lot easier to work with

trim ferry
#

The "former"?

clever spade
#

The first option suggested

trim ferry
#

bruh now he plays the animation on the corner of the map

#

i tried reseting the pos

#

the hieraryasd blabla idk how to write

oblique fractal
#

Using the Unity character controller with Photon Fusion's NetworkCharacterControllerPrototype and cannot get the player to stop sliding all over the terrain - it also starts jumping when i try to run up a hill (but not when i walk slowly). I've tried a Physic Material with friction, setting gravity, high and Raycasting to check for ground instead of using Unity CC isGrounded. No dice. Any idea what could be going on?

zealous bridge
#

Photon fusion uses it's own physics engine last time I worked on it

oblique fractal
#

and the isGrounded comes from the Unity CharacterController which I can't seem to find how that gets set

polar marten
oblique fractal
oblique fractal
#

that jump in there was involuntary lol

#

its pretty shaky too when im running

#

i have the character rotating based on the forward transform on the camera also as that may be relevant

primal garnet
#

You should rotate the player when you press the keys

oblique fractal
#

I had it like that before, but forward would be become backward, etc depending on which way you face the camera

primal garnet
#

Camera looks good

#

Add rotation to the body when you press the keys

#

You can think like gta 5

oblique fractal
#

ah yeah I have it when you press the W key to rotate the player where the camera is facing

#

if you arent pressing anything it will rotate around the player

#

my goal was to rotate with the camera and then strafe with A and D

primal garnet
#

Ohh

#

Ok

oblique fractal
#

but as soon as i hooked up the camera to player rotation, he started ice skating everywhere and can't run up a hill

solemn raven
#

Hey,
is it possible to lerp without the update() function ?

swift falcon
#

@polar marten tyty u got me on the right path

#

Avatars + Avatar Masks + Layers is what i was looking for

#

instead of using unity editor

unreal temple
#

Lerp just returns a value between start and end by percentage

#

So you can use it in many contexts

#

If you're trying to move some visual from one position to another you'd want to use it every frame though.

#

If you want a helper for moving things around you could check out DOTween

solemn raven
solemn raven
#

I cant use DoTween , I need to build it my own

unreal temple
#

I started writing my own tweening library, it's fairly involved

#

But if you just want to move things, it should be easy enough

solemn raven
#

its for a client who has a package on the asset store, and doesn't want his package to be dependent on another even if it was free, doesnt wanna get involved in a complex licensing and copyright situation

rancid sable
#

How do I use an interface as a variable in a job? using one gives the error: "InvalidOperationException: VoxelGenerationJob.densityGeneratorData is not a value type. Job structs may not contain any reference types" but I don't want to be confined to a struct since they do not have inheritance

hollow stone
unreal temple
# solemn raven that is the case im looking for, is it possible to make one script to handle all...
class Tweener : MonoBehaviour {
  static Tweener Instance { get; private set; }

  struct Tween {
    public Transform Transform;
    public Vector3 From;
    public Vector3 To;
    public float StartTime;
    public float Duration;
  }

  List<Tween> _tweens = new();

  public void Tween(Transform transform, Vector3 to, float duration) {
    _tweens.Add(new Tween {
      Transform = transform,
      From = transform.position,
      To = to,
      StartTime = Time.time,
      Duration = duration
    });
  }

  void Awake() {
    Instance = this;
  }

  void Update() {
    using var _ = ListPool<int>.Get(out var toRemove);
    for (var i = _tweens.Count - 1; i >= 0; iii) {
      var tween = _tweens[i];
      var end = tween.StartTime + tween.Duration;
      if (Time.time > end) {
        tween.Transform.position = tween.End;
        _tweens.RemoveAt(i--);
      } else {
        var progress = Mathf.InverseLerp(tween.StartTime, end, Time.time);
        tween.Transform.position = Vector3.Lerp(tween.From, tween.To, progress);
      }
    }
  }
}
hollow stone
solemn raven
rancid sable
#

what if you need an unknown amount of types passed in?

#

nvm

rancid sable
#

thx

visual flare
#

how do you get Drawgizmos to display opaque cubes? no matter the color it's 50% transparent.

rancid sable
ionic socket
#

once upon a time, was the square root of zero = 1? Does anyone else remember being taught that?

solemn raven
#

hey,
what is the right way to change canvas child object opacity?

vagrant blade
#

Give it a canvas group component and change the alpha.

solemn raven
vagrant blade
#

Unless the child is just a single image component, then you can just change the colour directly.

grim copper
#

how do you code and reference post process volumes and layers in unity

#

ive been trying since midnight

#

its 2;35 now

#
    private ChromaticAberration chromaticAberration;
    private Grain grain;
    private LensDistortion lensDistortion;


void Start() {

PostFX.GetComponent<ChromaticAberration>(out chromaticAberration);
PostFX.GetComponent<Grain>(out grain);
PostFX.GetComponent<LensDistortion>(out lensDistortion);


}

doesnt work

soft shard
# grim copper ```public PostProcessVolume PostFX; private ChromaticAberration chromaticAbe...

Might be a newer version or cause im using HDRP, but for my game, this is how I access it, you may only need need to change "GetComponent" to "TryGet" (technically, its not a component, they are "overrides" on a stack of the profile asset) - make sure you have your using UnityEngine.Rendering namespace, then:

public class SomeScript : Mono
{
[SerializeField] Volume fx;

ChromaticAberration blur;
LensDistortion distort;

void Start()
{
fx.profile.TryGet<ChromaticAberration>(out blur);
fx.profile.TryGet<LensDistortion>(out distort);

fx.weight = 0f;
}
}
visual flare
high condor
#

does anyone know why this script doesn't work ONLY when I add the PlaySFX() method?

#

it does't matter where I put PlaySFX() in the Attacked() method :T

leaden solstice
#

Did you check the console?

high condor
#

the console doesn't tell any errors

leaden solstice
#

Try putting breakpoint and debug

high condor
#

HUH

#

I close and open unity and it works

#

whack game engine

paper pond
#

Is there a reason why sometimes the rotation of my object is Slerped and other times it isn't?

IEnumerator Rotate(Vector3 rot, float lerpDuration)
    {
        float timeElapsed = 0;
        targetRotation = Quaternion.Euler(rot);
        while (timeElapsed < lerpDuration)
        {
            transform.rotation = Quaternion.Slerp(transform.localRotation, targetRotation, timeElapsed / lerpDuration);
            timeElapsed += Time.deltaTime;
            yield return null;
        }
    }
high condor
quaint rock
#

also for that to be a proper slerp over a set amount of time you would need to cache the starting rotation

#

its acting more like a move towards then a slerp due to feeding it a constantly changing rotation for slerps first arg

quaint rock
paper pond
#

yea that was a typo

#

i have it set as local for both

urban owl
#

Hi, if a gameobject has a material and mesh,
I want unity not to pack this material and mesh when Build.
how can I do this?

quaint rock
#

otherwise, yeah just cache your current rotation before the while loop, and pas that into the slerp instead of the current local rotation @paper pond

dapper hinge
#
public IEnumerator AnimateBubbleText()
    {   
        //text alpha starts at 0
        for (int i = 0; i < mainText.Length; i++)
        {
            //make i'th character alpha 255
            textComponent.ForceMeshUpdate();
            TMP_TextInfo textInfo = textComponent.textInfo;
            int materialIndex = textInfo.characterInfo[i].materialReferenceIndex;
            int vertexIndex = textInfo.characterInfo[i].vertexIndex;
            
            Color32[] vertexColors = textInfo.meshInfo[materialIndex].colors32;
            vertexColors[vertexIndex + 0].a = 255;
            vertexColors[vertexIndex + 1].a = 255;
            vertexColors[vertexIndex + 2].a = 255;
            vertexColors[vertexIndex + 3].a = 255;
            
            textComponent.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);

            yield return new WaitForSecondsRealtime(0.05f);
        }
    }

Can anyone help me figure out why this code produces this behavior? It's supposed to updated the alpha of each character to 255 and keep it that way.

paper pond
#

ok it works thanks @quaint rock

soft shard
# grim copper I believe im on the URP.

I think it should work the same, in requiring TryGet, it just may be in HDRP or newer version of the post process stack, that its just called "Volume" instead of "PostProcessVolume", the structure of the code should be the same though AFAIK

grim copper
# soft shard I think it should work the same, in requiring `TryGet`, it just may be in HDRP o...

I tried 'Volume', says the namespace can't be found,

then did this.

        PostFX.profile.TryGet<ChromaticAberration>(out chromaticAberration);```

and i get 

'PostProcessProfile' does not contain a definition for 'TryGet' and no accessible extension method 'TryGet' accepting a first argument of type 'PostProcessProfile' could be found (are you missing a using directive or an assembly reference?)
#

trygetcomponent doesnt give any errors but then just doesn't work.

ionic socket
#

transform.localPosition = transform.parent.position - transform.position, is that right?

ionic socket
soft shard
grim copper
#

weirdly, it wants PostFx.GetComponent etc

#

not PostFx.profile.GetComponent

safe knoll
# grim copper the post process effects just don't apply

what version of Unity are you on?

i just tested with URP 2021.2.11f1

the following worked fine for me.

Volume volume = FindObjectOfType<Volume>();        
if(volume.profile.TryGet<ColorAdjustments>(out var colorAdjustments))
{
    colorAdjustments.saturation.value = 999;
}
if(volume.profile.TryGet<Bloom>(out var bloom))
{
    bloom.intensity.value = 50;
}
grim copper
#

i was on a 2020 version wtf

timid meteor
#

How could I add a transform.posistion to this so I can choose where the grid spawns?

zealous bridge
#

call it offset

#

or a baseOffset if it is confusing...

#

and add that to the noiseMap, fallOfMap and grid?

slender nacelle
#

hi guys, this honestly feels like the dumbest question, im trying to get my pathfinding implementation using dots to work, im not stuck on the dots part, im stuck on the assigning a grid to an int index.

  1. how to calculate the node index 'correctly' to minimise the size of the array needed
  2. how do i calculate the max array size when i create it?
    I think these are more maths but im strugglin
    private int CalculateNodeIndex(int x, int z, int yLevel, int gridSize)
    {
        return (x + z * gridSize/2) + yLevel;
    }
NativeArray<PathNode> pathNodeArray = new NativeArray<PathNode>(_cells.Count * 25, Allocator.Temp);
lusty lily
#

I am currently making a rope system from scratch and I have ran into a problem. I'm trying to detect when a player is on a single segment to calculate which segment to move to next. The issue is that the OnCollisionEnter2D is recognizing multiple of the segments and then the player's position is rotated between every single segment, not allowing me to move. Is there anyway I can fix this? Thank you! (I can send code and screenshots if needed) : )

wild nebula
#

Anyone familiar with encryption?

        public static void GenerateKeyAndIV(out byte[] key, out byte[] iv, string seed)
        {
            using (TAlgorithm algorithm = new TAlgorithm())
            {
                int blockSize = algorithm.BlockSize;

                var derivedIVBytes = new Rfc2898DeriveBytes("SomeStaticIV", blockSize, 10000);
                var deriveKeyBytes = new Rfc2898DeriveBytes(seed, blockSize, 10000);

                byte[] ivBytes = derivedIVBytes.GetBytes(blockSize);
                byte[] keyBytes = deriveKeyBytes.GetBytes(blockSize);

                algorithm.IV = ivBytes;
                algorithm.Key = keyBytes;

                iv = algorithm.IV;
                key = algorithm.Key;
            }
        }

I keep getting System.Security.Cryptography.CryptographicException : Specified initialization vector (IV) does not match the block size for this algorithm. when trying to use this key/iv to encrypt/decrypt.

#

TAlgorithm is where TAlgorithm : SymmetricAlgorithm

dim furnace
#

Why dosent this reset the bool?

#

It lets me shoot infinite times when I want to wait 2 seconds

dusk apex
#

if( ... = ...)

#

=

dim furnace
#

How do I fix that then

wispy nacelle
#

Is Input.Touch synced with EventSystem?

dusk apex
#

You'd probably want the equality operator rather than assignment operator ||==||

wispy nacelle
#

Or may I use them together?

dim furnace
#

Yeah that fixed it thanks

wispy nacelle
#

I want to detect when a specific touch is released on a certain UI element, and I use IPointerEnterHandler and IPointerExitHandler to detect if said touch is over that UI element

rain nymph
#

Is there a code solution to gif support?

wispy nacelle
#

How do I know if the pointer that invoked OnPointerDown has been released?

south gorge
#

my whole game dissapeared

#

while i was working on it

somber nacelle
#

not really a code question. but are you sure you didn't just open an empty scene?

south gorge
#

I was working on it and it crashed

#

and i reopened the file I was working on

#

and its an empty scene

somber nacelle
#

had you ever saved the scene?

south gorge
#

yea

#

i have been working on it for a while now

somber nacelle
#

and you are certain you have actually opened that scene? and not just assumed it would open automatically when you started unity again?

south gorge
#

i found it

#

sorry

#

ty

dim furnace
#

Why am I getting this error?

somber nacelle
#

first, configure your !IDE

tawny elkBOT
#
๐Ÿ’ก IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

somber nacelle
somber nacelle
#

provide the correct number of arguments

#

there's even an example of how to use it on that page

dim furnace
#

ok cheers

unreal temple
#

Does anyone know where to get a list of C# namespaces not supported by IL2CPP?

#

(I recall that being a thing, if not then even better)

kind niche
unreal temple
#

Trying to work out if I can use ConditionalWeakMap

jovial crow
#

Why does it do this? the game runns fine in the editor but as soon as i try to build i get a ton of errors?

dense cloud
#

just pseudo code but,
why is my variable of a specific class null if I don't equate it to GetComponent?

somber nacelle
#

make sure you put your editor-only code into a folder called Editor so it is included in the editor assembly. or wrap it in conditional compile preprocessor directives

vestal crest
#

how do you ease lerp

dense cloud
#

Does the GetComponent allows access to it's properties?

#

of a specific class

#

I kinda thought you can access the components directly after creating a variable of the class

somber nacelle
mellow sigil
#

You don't access a class. You access instances of a class.

dense cloud
#

ah an object

somber nacelle
mellow sigil
#

You could have any number of colliders in the game. You have to tell it which collider you want to access.

dense cloud
#

gotcha, thanks for the breakdown ๐Ÿ‘

dense cloud
somber nacelle
#

yes, unless you call GetComponent on a reference to some other object

dense cloud
#

ooo thanks again

ivory spade
#

Sup! I have some issues, this is one of them. Anybody have any insight on what went wrong and how i can fix it?

somber nacelle
south violet
#

Hi, I have a problem with tests. Every test passes in unity, but on CI in git one of tests has time out after [TearDown] method which actually just destroys all gameobjects. Each one of my tests is using the same [TearDown] method since all of them are deriving from the same class for tests. And I have no idea what could go wrong with this one test

coral kettle
#

couldn't really find much info googling this, but does anyone have a way to like, get a number between 1-20 based on a string?

I want to take for instance, a players character name and get an int, 1-20 based on the name

somber nacelle
#

how would that even work? ๐Ÿค”

mellow sigil
#

What's the logic that determines what number you get?

coral kettle
#

that's what I'm looking for ideas on

somber nacelle
#

there are certainly more than 20 possible strings, how would you determine what number you get and how would you also prevent collisions?

coral kettle
#

I'm literally just looking for a way to map a string to 1-20

#

collisions are fine

somber nacelle
#

collisions as in two strings mapping to the same number, not physics collisions with colliders

coral kettle
#

yeah, that is fine

#

two strings should map to the same number

#

I mean

#

there are only 20

somber nacelle
#

please read the link i just gave and explain the purpose of what you are trying to do

mellow sigil
#

Put all of them in an array, then get the index in the array + 1

craggy cedar
#

What's up with VS adding using Codice.Utils when autocompleting some stuff

coral kettle
mellow sigil
#

but why do you want it based on the name specifically

somber nacelle
#

well one way is you could add up the integer values of the individual characters then just % 20 it, but also the entire premise of this makes very little sense

coral kettle
#

because that is the only information that I can get, a string of their name

somber nacelle
#

why is that the only information you can get? it's your game, no? just have them select a number

coral kettle
#

I thought of that but I felt that might be weighted pretty high in general

somber nacelle
#

ah yes, better be picky about the solutions for an issue that makes no sense in the first place ๐Ÿคทโ€โ™‚๏ธ

coral kettle
mental rover
coral kettle
unreal temple
#

Does anyone have a simple way to clear cached info when entering/leaving play mode when domain reload is disabled?

#

I'd like to cache some data in SOs, but make sure that it's invalidated in each play.

#

I guess clearing it in OnValidate might be sufficient, but that feels like it could break.

coral kettle
somber nacelle
#

show the code you used because doing it the way i suggested gets a decent spread of results if you take into account the different ways people may create their usernames

mental rover
unreal temple
#

like cached calculations

#

Derived from the persistant config of the SO

mental rover
#

I'm not sure if that answers why it needs to be in the SO - just create another object to act as the cache at runtime?

#

if it's supposed to only be runtime data and wiped/invalidated after exiting

unreal temple
#

Which is functionally the same thing, but the advantage is I can clear it in RuntimeInitializeOnLoad

#

Maybe that is the best move.

#

I think the purpose of SOs is to have a nice interface for serialized project data, not for persisting data between runs

#

If you're using it for that you'll have a bad time when you build

#

But it sounds like you probably already know this

thick heron
#

how do i deal with raycast collisions between multiple objects

#

like check each one

unreal temple
#

That will let you get all contacts on your raycast

mental rover
unreal temple
#

Yeah, hence my question.

#

The cache won't be serialized

#

I just want to make sure it's cleared before I enter play mode so I can recreate it lazily

hexed pecan
#

I like how everyone has a different opinion on how SO "should" be used

unreal temple
#

I am using them the right way.

#

:-)

mental rover
#

I mean, I guess, but it seems a bit like having a full box of different coloured crayons in front of you, picking a red one, and then saying "how can I change this so it isn't red"?

#

anyway - I'm sure EditorApplication will have what you're looking for ๐Ÿ‘

unreal temple
#

lol

#

I am using SOs to store configuration data for weapons and projectiles

#

In answer to your question

#

And I am asking what a good way to store derived data from that config is

hexed pecan
unreal temple
#

I wrote the wrong thing

#

I mean persisting data in the build

#

in the project

#

wait that is what I wrote

#

...

hexed pecan
#

Im agreeing

unreal temple
#

Haha, I misread my own comment

#

Yes. :-)

#

Yeah, doesn't make sense to persist data between runs

#

It will just make your project run differently in editor to build

#

Well, I would say that was the quintessential unity discord experience.

#

Asked a question, got told I was wrong for asking until the question got pushed above the fold lol

hexed pecan
#

Relatable

coral kettle
somber nacelle
#

that's exactly what i was suggesting. a string is made up of multiple characters (or char) and a char is a character represented internally by an integer so you can cast it to int to get that integer value

#

you'll want to +1 that playerID though unless you want values from 0 to 19 instead of 1 to 20 (inclusive)

coral kettle
#

ah ok, 0-19 is fine. thanks for the help! sorry if the question wasn't very clear

mental rover
coral kettle
#

the way I tested it at first was really dumb btw. I didn't know about a string with characters being represented internally by integers so I literally sat there and was like "a = 1 b = 2"

thin kernel
#

Silly question. Is there a way to do a one line if statement without an assignment? It's possible in some other languages but maybe not in c#?...

I can do this:
_ = correctAnswer ? AnswerIsCorrect() : AnswerIsIncorrect();
but only if functions have a return value.

I mean it's so seductive to do it in one line, so natural, instead of 6 or 4 with standard if statement. Very silly question, i'm sorry :D

somber nacelle
#

no, ternary operator can only be used with assignment

#

you could just do if(correctAnswer) AnswerIsCorrect; else AnswerIsIncorrect; all in one line if you must have one line

ivory spade
#

Anybody got any ideas on what kind of object reference i could use?

unreal temple
ivory spade
somber nacelle
#

also configure visual studio !vs

faint horizon
#

Hi there. Does anyone know how to get the name of a specific sprite assigned to a SpriteRenderer that's been taken from a spritesheet? I've tried using sprite.texture.name but that only tells me the name of the sheet itself and not the sprite within the sheet that the SpriteRenderer is using. Any ideas how I can access that name via code? Thanks! ๐Ÿ™‚

somber nacelle
#

!ide

unreal temple
#

!code

#

hm

somber nacelle
#

seems the bot died

unreal temple
#

I thought there was a bot

tawny elkBOT
#
๐Ÿ’ก IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

somber nacelle
#

oh there it goes

unreal temple
#

there we go

unreal temple
unreal temple
#

Your code has a class before the .

#

IT's just hard to tell there's a compile error because you haven't set up your IDE, which you should do before asking more questions.

faint horizon
#

@somber nacelle Initially I assign a sprite to the renderer. This will later change in game and I need to remember the original sprite assigned

unreal temple
somber nacelle
unreal temple
#

I haven't used spritesheets much

faint horizon
#

OK. Any quick tips on how I'd do that?

unreal temple
faint horizon
#

Thank you! ๐Ÿ™‚

#

Much appreciated

urban owl
#

if I have reference a resource in MonoBehaviour, how to ask unity not to pack this resource when Build?

hexed pecan
#

Are you talking about the Resources folders specifically?

urban owl
hexed pecan
#

Nvm then

urban owl
#

such as a model or texture

hexed pecan
#

You can call it an asset

#

But its a good question, idk

urban owl
#

I want something like this :
[NotPackToGame]
Texture tex;

somber nacelle
#

but why? ๐Ÿค”

#

surely if your code relies on a reference to something you would want that object to be included in the build, no?

urban owl
hexed pecan
#

You could have editor specific code

#

With preprocessor directives

urban owl
#

for example?

hexed pecan
#

Im on mobile, boxfriend go at it

hexed pecan
#

#if UNITY_EDITOR etc

somber nacelle
#

i'm not entirely sure how well it plays with including/excluding assets from a build though. but if you are normally assigning the variable in code when in a build, just mark it as NonSerialized only for when not in the editor. or if you don't even use that variable in the build then just get rid of the entire variable in the build with the preprocessor directives

urban owl
#

this is too risky

#

maybe different between versions

trim schooner
#

Could have a build process to find it and remove it

daring cove
#

How to not make this lerp the position?
Right now it makes the other object go to the next one at the given speed ignoring the distance between.


private void Update()
{
    direction = nextTrackLink.transform.position - transform.position;
    float lSpeed = speed * Time.deltaTime;
    transform.position += lSpeed * direction;
}
somber nacelle
#

you probably want to normalize the direction

#

but also i don't understand what you mean by "at the given speed ignoring the distance between"

daring cove
#

No matter the distance between transform.position and nextTrackLink.position it takes speed amount for transform.position to reach nextTrackLink.position.

somber nacelle
#

normalize the direction when you multiply it by lSpeed

vague slate
#

Does Unity Object instance ID has any sort of NaN number?

#

Some value that is never going to be assigned to instanceID of Objects?

somber nacelle
#

probably not

buoyant crane
#

it does mention briefly how they are assigned

terse venture
#

Hi, just wondering if someone could point me in the right direction. Im wanting to code a minigame where you clean an object, bit like pressure wash sim I suppose. I know id be needing a dirt map, and to use a brush texture to remove that texture, but I cant find anything to help with being able to code this, Ive never worked with shaders before.

vague slate
#

not much of a value for my use case, but I think simple description hints me that it can't be 0

vagrant oasis
#

Hey, so i want to make a system, that when ur mouse is near a object that have "Interactable" script, it sets the ui position to this object position. I already tried doing Ray tracing with Dot product, doing sphere Overlap and i tried converting all of the objects to screen space and checking which is the closest to mouse position but that didn't work, right now im using dot product and ray tracing and it works but i want to disable ui when the dot product doesn't detect any object with interactable script
My current script (inside update):

                float closest = 0f;
                Ray ray = playerCameraInstance.ScreenPointToRay(Input.mousePosition);
                Interactable[] interactables = FindObjectsOfType<Interactable>();

                foreach (Interactable interactableObj in interactables)
                {
                    
                    Vector3 vector1 = ray.direction;
                    Vector3 vector2 = interactableObj.gameObject.transform.position - ray.origin;

                    float lookPercentage = Vector3.Dot(vector1.normalized, vector2.normalized);

                    if (lookPercentage > 0.9f && lookPercentage > closest)
                    {
                        closest = lookPercentage;
                        interactionUI.position = playerCameraInstance.WorldToScreenPoint(interactableObj.transform.position + Vector3.up * yOffsetInteraction);
                    }
                }
sterile echo
#

How monebehavioure can call start awake and other methods when i set there access modifier as private, does that mean they are called using reflection?

rain minnow
sterile echo
#

by non clean i mean that private methods can't be called by parent class in pure c#

cold parrot
rain minnow
swift falcon
#

Hey guys does anyone know the API where i can add bone transform keys to my avatar pragmatically

#

I know we have this but this doesn't let you add bone transform keys
Avatar avatar = AvatarBuilder.BuildGenericAvatar(activeGameObject, "");

#

Or will it do this automatically?

vestal summit
#

YO WHERE DID TIME.DELTATIME GO????

#

WAIT NVM

#

lol

#

dw

#

I forgot I had a class called Time

polar marten
swift falcon
#

Main bones which are not shared, so i can play different animations on them

#

My animator will have these layers

#

with the Mask created and synced to base layer

#

then override animation controlller can do the rest of the job

#

๐Ÿฆพ

#

great time to figure out how to save masks

#

actually im just gonna point the masks manually to assets

polar marten
#

okay just to confirm you are not

#

creating keyframes manually anymore right?

#

when you said bone transform keys, you meant the mapping from the transform hierarchy to the animation hierarchy*?

#

which is what an avatar is ๐Ÿ‘€ so my expectation is it should be configurable somehow

swift falcon
#

i am not

#

๐Ÿ˜„

#

I tested the masking and it worked

#

but i need to generate the mask keys with a script

#

in the editor instead of manually doing it for every model

floral coral
#

If multiple buttons (in the UI) all trigger one function in a script, how can the function know which button has been pressed? Do I have to make multiple functions for each button that each call the function that does something with an "ID" for each function called by the buttons?

steady thicket
#

Is this an appropriate place for me to ask for some feedback on some code that I've written or where is a good place to do that?

polar marten
#

sorry i misunderstood

polar marten
#

if you are using the inspector to wire up your buttons

#

you can pass a single argument

floral coral
polar marten
polar marten
#

i don't understand

#

why you would organize it like
button 1 all go into -> function ---> function 1
button 2 function 2
button 3 function 3
button 4 function 4

floral coral
#
public void ButtonBody()
    {
        ChangeTab(0);
    }

    public void ButtonMechanic()
    {
        ChangeTab(1);
    }

    public void ButtonGround()
    {
        ChangeTab(2);
    }

    public void ButtonInput()
    {
        ChangeTab(3);
    }

    public void ButtonOutput()
    {
        ChangeTab(4);
    }

    public void ButtonMisc()
    {
        ChangeTab(5);
    }

    public void ChangeTab(int buttonID)
    {
        //code here
    }
polar marten
#

yeah

#

why don't the buttons directly call changetab

#

if you're wiring it up in the inspector

#

you can pass the argument in the inspector @floral coral try it

floral coral
#

I don't know how

  • that's why I came here
polar marten
#

simply choose changetab

#

instad of buttonground

#

you should observe you can choose ChangeTab in the dropdown for the on click part of the inspector for your Button component

floral coral
#

Ohh, I had to save it to see that

#

Thanks!

steady thicket
#

I've been working on a system to handle things like daily schedules for NPCs and other things that make sense to happen in "Game Time" rather than real time. I don't have any kind of formal background or a lot of experience in coding and in this system am using some things I'm not super familiar with (like delegates and actions). I was really just hoping maybe I could get some general feedback on it to see if it seems generally sensible.

Here is the script for the main TimeManager system: https://paste.ofcode.org/ZNvUii5m6FxLWe8XifYHNJ

And a small script I'm using to test it currently to show how it can work: https://paste.ofcode.org/As6ZRkyLQGycPgmrePdSnM

I would really appreciate any feedback anyone can give me honestly.

orchid bane
#

I have such a tween from DOTween:

var tween = transform.DOMove(destination, (destination - transform.position).magnitude / speed);```
How do I change its duration midway? (i.e. in update)
#

I mean I want my character to get a sudden speed boost

hard sparrow
#

How to do this?

swift falcon
#

Modinstance type will be inferred

#

Your using a Type T in AddComponent right now

hexed pecan
#

Why not just make it take a parameter of type Mod?
Oh wait I see what youre trying now

warm stratus
#

hey, how do you find the game_id of a project?

polar marten
warm stratus
polar marten
mild timber
#

I have been told my game could use some more "bounce". My project is already using DOTween, but someone recommended to me that LeanTween would be good for this and showed me a decent looking tutorial

1)is it bad form to import both DOTween and LeanTween into a project when they really do the same thing
2) does anyone have thoughts as to which would be better (or potentially a 3rd option) for adding some 'bounce' to a game?

If you wanna see it (this version only works in Full HD 1920 * 1080)
https://galahadgaming.com/Games/Builds/

hexed pecan
steady thicket
hard sparrow
#

Once I attach the component I can just do mod.BindToUnit

steady thicket
#

Or do you mean something else like am i saving it somewhere and loading it in?

#

across multiple sessions, because also that.

polar marten
#

okay

#

i haven't looked at your code yet

#

but that can be pretty tricky

#

even people with a formal programming background, like me - when i first learned how to do this correctly it wasn't at all obvious

hard sparrow
#

I guess the only way to do this is to have a library of prefabs (one for each type of Mod) and then have it pull from that

polar marten
#

is your game like an animal crossing game?

hexed pecan
hard sparrow
hexed pecan
#

Probably coupling the mods with an enum

steady thicket
#

@polar marten I mean I haven't currently put in a way to save and load the time, but the actual saving i can handle since i'm storing it as a long, so it would just be a matter of putting in a method my save manager can call to set the property currentTime, I believe.

polar marten
hard sparrow
polar marten
#

or some kind of rpg, where characters move around in real time and do stuff?

steady thicket
#

No this is an rpg

hard sparrow
#

or having a big switch statement

hexed pecan
#

Maybe a Dictionary<MyEnum, GameObject>

austere orbit
#

Hi, how can I change the default position of the content of Scroll Rect? Green area is the Panel with the Scroll Rect component and red area is content of it. I would love to have that content on the top of green area but I have no idea how to do that. Does anyone have any ideas?

polar marten
#

is it possible for your npcs to have done stuff while the player has not been playing @steady thicket ?

hard sparrow
#

I'll buy the goose right now!!

polar marten
#

@steady thicket the punchline to all of this is, what is the design space of what you actually want to do?

hexed pecan
#

@hard sparrow Be aware that dictionary isn't serialized by default so you'd need to generate it or use SerializableDictionary for example
Or hard code it but thats less flexible

steady thicket
#

@polar marten well my plan is that each will have a schedule of where they are at any given time, when a scene is loaded they'll be placed where they should be, but nothing will actually happen unless the scene is loaded. Does that answer your question or did you mean something else?

hard sparrow
#

Yes I was actually already using that method for something else. Just wanted to see if there was a more on the fly way to do it

steady thicket
#

then as the game plays they will move to different places and do different things as time progresses

swift falcon
#

Hey guys, So i created a pause menu for my 3d game. Everything is working fine but when I press ESC the Pause Menu pops up but my game doesnt freeze I can hover around by my mouse and my character looks here and there. Here is my Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.SceneManagement;

public class pausemenu : MonoBehaviour
{
public static bool GameIsPaused = false;

public GameObject pauseMenuUI;


void Update()
{
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        if(GameIsPaused)
        {
            Resume();
        }
        else 
        {
            Pause();
        }
    }
}

public void Resume()
{

    Cursor.lockState = CursorLockMode.Locked;
    pauseMenuUI.SetActive(false);
    Time.timeScale = 1f;
    GameIsPaused = false;
}

void Pause()
{

    pauseMenuUI.SetActive(true);
    Time.timeScale = 0f;
    GameIsPaused = true; 
    Cursor.lockState = CursorLockMode.Confined;
   
     
}

public void Loadmenu()
{
    GameIsPaused = false;
    Time.timeScale = 1f;
    SceneManager.LoadScene("menu");
}
public void QuitGame()
{
    Debug.Log("Quitting Menu...");
    Application.Quit();
}

}

steady thicket
#

following their schedule

hexed pecan
#

Bot is slacking, rip commands

swift falcon
steady thicket
#

But I'd also like to implement some other things that make sense with this system, examples could be things like the player is well rested for 4 game hours or sick for 3 game days or something.

polar marten
#

here is an example of interesting npc rpg gameplay:

// a villager who gathers berries to sell them at the market
public async Task BerryGathererLoop() {
 while (!Dead()) {
  try {
   await WakeUp();
   var berries = await FindBerries();
   await GoTo(berries.position);
   await Gather(berries);
   var market = await Find<Market>("Market");
   await GoTo(market.position);
   await market.Trade(this, berries);
   // in this loop I go home
   await GoToSleep();
  } catch (OperationCancelledException) {
   // this goes to another loop where
   // the villager checks if he's hungry, sleepy,
   // low health, etc. and tries to resolve
   // those exceptional issues. we assume if
   // the villager fails here, the villager died.
   await TryToStayAlive();
  }
 }
}
#

@steady thicket making this piece of code work is hard

#

but on the other hand, you know exactly what the npc is going to do. it's very expressive

#

i'm not saying you have to do this. but if your design space - the scope of what you want to achieve - is "all possible RPG behaviors" - this is hard

#

that's why i am asking what you want to do

steady thicket
#

@polar marten Well this particular system isn't about behavior, it's purely about keeping track of time and calling methods when it's at least a certain time. I understand what you mean about how things can get very complicated quickly, though. My system does what I want it to do currently in the tests I've done, I just don't know if I'm way out in left field or not with how I'm achieving this.

steady thicket
#

Just looking over the code since I posted it I've noticed a couple of weird ways of doing things that are left over from earlier iterations of the code here and there and a few naming inconsistencies, I went over it a few times before posting but still missed a couple of things it seems, so ignore that kind of stuff if you do look at it lol.

swift falcon
#

Hi labs, this is my script to get rewarded by passing the points which are need it to activate the new character. How can i set in that user, which download my app, starts from beginning? Because if you download my app right now you have the new character but thatโ€™s wrong. Everyone should start from zero, so collecting the limit of points to activate

https://hastebin.com/share/ipaqaxiziv.csharp

nova python
#

am I using clamp wrong? Output always shows the y velocity as 0 and player falls very slowly

#

velocity will be negative as this function is run when player has reached highest point of jump

dusty badger
nova python
#

I thought it was always max first

#

I guess I'm zooted mb lol

dusty badger
#

is there a way to have new sprites/textures automatically do all the 2D pixel perfect settings, like setting the pivot for individual sprites? i have the preset setup for textures but is there a tool or scripting solution something?

cobalt elm
#

What exactly is loadsceneasync? i know it loads in the background but how specifically does it load? does it just function like loadscene or does it load the data and then you can actually like "load" it to where its visible. Also if I have a scene queued up with loadsceneasync wont it just hog up memory?

dusty badger
#

im not sure if it loads pieces of the scene one by one and you could theoretically do something in between each gameobject on the main thread while its loading, but it drops everything into the scene automatically

#

typically you use the progress variable and wait for it to be over, but you can do stuff like animating a loading screen on the main thread without the program freezing

#

im not sure what you mean by hogging up memory here

#

if you use Additive mode it will layer the scene on top of any scenes already loaded, if not then i think everything gets unloaded apart from DontDestroyOnLoad stuff, generally i think thats it but i might be inaccurate in some way

cobalt elm
#

Thank you!

vestal crest
#

i move my character with navmeshagent.move and i have objects that follow player

#

but when i increase lerp speed of objects its jittering

#

its like very laggy

#

i tried to lerp in all updates but still laggy like it updates immedialty every 10 frames or smth like that

sacred frost
#

code?

vestal crest
dusty badger
#

its your interpolant, t parameter

dusty badger
# vestal crest

t is how far along on the line between A and B you should move, giving a speed will not move the same distance, you can calculate T by doing (target - current) / speed * time.deltatima

leaden ice
#

You just want something like this, no?

float timer = 0;
float multiplier = whatever;

void Update() {
  timer += Time.deltaTime;
}

const int SecondsInMinute = 60;
const int SecondsInHour = SecondsInMinute * 60;
const int SecondsInDay = SecondsInHour * 24;

public float ScaledTime = > timer * multiplier;
public int Seconds => Mathf.FloorToInt(ScaledTime);
public int Minutes => Mathf.FloorToInt((ScaledTime / SecondsInMinute) % 60f);
public int Hours => Mathf.FloorToInt((ScaledTime / SecondsInHour) % 24f);
public int Days => Mathf.FloorToInt((ScaledTime / SecondsInDay));```
#

Time.time and deltaTime will both freeze when setting time scale to 0

#

if you want to not have that happen you use Time.unscaledTime and Time.unscaledDeltaTime

dusty badger
# vestal crest

sorry i had to write that quickly, its actually t = (target - current).magnitude / (speed * Time.deltaTime)

#

wait im an idiot

#

there it is, magnitude

vestal crest
#

i mean yeah i added magnitude earlier but

#

i dont think t is okay with this

#

its jittering now when followspeed is less than before

#

its actually teleporting

dusty badger
#

uhhh

vestal crest
#

not even lerping

dusty badger
#

wow i really keep messing that up off the top of my head thats my bad

vestal crest
#

i dont think using distance here makes sense

dusty badger
#

the ratio is amount traveled per frame / total distance

#

i gave you the inverted ratio so flip it

#

am i misunderstanding your code then? you want to move from current position to target position over time?

#

t = (speed * deltaTime) / (target - current).magnitude is what i use, my bad

vestal crest
#

still doesnt work correctly

rocky shoal
#

I am making a UnityWebRequest to the following local url (it's a simple server manager) and checks to see if a room exists and if so returns the port to connect to - https://localhost:7106/Server/Find?roomCode=ABCD the url works perfectly everytime in something like PostMan, but Unity seems to be sending it weird. Are query parameters not supported? If not, what do you recommend?

leaden ice
#

and maybe explain what you mean by "Unity seems to be sending it weird"?

rocky shoal
#

@leaden ice I'm sending it via

using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))

When sending via UnityWebRequest, roomCode will randomly contain a ? at the end of the roomCode variable and it shows up in the Console.WriteLine step

leaden ice
#

print it

#
Debug.Log($"URI is: '{uri}'");```
dusty badger
rocky shoal
#

The Debug.Log occurs the line before the Get UnityWebRequest

leaden ice
#

with ' ' surrounding it

#

you might have some extra weird invisible character at the end or something

mental anvil
#

So i am getting the null reference exception and it seems camera.LookAt isn't working with the Cinemachine Free Look Camera. How can I swap the Look At Target?

rocky shoal
#

@leaden ice This is the output immediately before sending (with UnityWebRequest) and the Searching db is the immediate check on the webapi side outputting the roomcode variable

leaden ice
rocky shoal
simple egret
# rocky shoal Yep, trying it with a non-query parameter /shrug

Are you getting that URI from an Input Field? If yes you might want to make sure the variable is of type TMP_InputField, and especially not a reference to the underlying Text it uses to display your input, as it adds an invisible character at the end.

leaden ice
#

if you really want real months/days/years etc

#

otherwise you will be in hell dealing with the logic and the exceptions

rocky shoal
#

@simple egret mm, so this should be changed to

var roomCode = RoomCode.GetComponent<TMP_Input>().text;
simple egret
#

Yeah definitely

#

That gets the underlying display text

vague slate
#

I am having a very odd problem: I load game object through AssetReference (addressables). Instantiate it. Aaaand, it's Awake is not called, Quite literally.

            var operation = _editorPrefab.LoadAssetAsync<GameObject>();
            await operation;
            if (operation.Status is AsyncOperationStatus.Failed) throw new("Failed to load editor prefab");
            var editor = Instantiate(operation.Result);
#

is there something I don't know about dynamically loaded assets?

rocky shoal
#

@simple egret @leaden ice That did it. Thanks for the help both of you!

leaden ice
#

time scale is irrelevant. You would just do this:

TimeSpan elapsedTime = TimeSpan.FromSeconds(timer);
DateTime currentTime = startTime + elapsedTime;```
#

then you can do currentTime.Days etc..

#

timer is a number you keep track of and increment etc

#

so the scale would be already dealt with there

whole night
#
 private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("bowlingpin"))
        {
            Destroy(collision.gameObject);
        }

    }

I have this script attached to the ball and if the ball collided with anything i check the tag
but on the editor it gives me the error that the Tag : bowlingpin is not defined.

solemn raven
#

Hi,
is it possible to run a function when enum value changes ?

leaden ice
leaden ice
#

apparently you haven't

whole night
#

I have defined it in the editor

#

oh wait there is a typo

leaden ice
#

errors don't lie

whole night
solemn raven
leaden ice
solemn raven
orchid bane
#

Can you share with me your code for a ball in basketball game? There are various guides but most of them dive into theory which I really do not need

dusty badger
#

if all you need is a bouncing ball you dont need any code for that i think just physics component

sacred frost
orchid bane
#

No physics allowed for it. Anyway just fixed a bug and now it's working

timid meteor
#

I have been working on a terrain generator and I have got it to work but the only issue is that I can't seem to find a way to move the tilemap so the terrain generates elsewhere.

#

Anyideas?

#

Here is what I have somewhat tested so far

#

//gets tilemapย  ย  //Tilemap tilemap = GetComponent<Tilemap>();ย  ย  //BoundsInt size = tilemap.cellBounds;ย  ย  //TileBase[] allTiles = tilemap.GetTilesBlock(size);

and this is the only source that I found helpful

https://forum.unity.com/threads/tilemap-tile-positions-assistance.485867/

https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap-origin.html
Unity - Scripting API: Tilemaps.Tilemap.origin

mental anvil
#

How can you set a LookAt Target for a Cinemachine FreeLookCamera via script?

fiery path
#

Really stupid question but is there a simpler way of doing this rather than having an almost instant invoke?
Without the invoke, the RB constraints are only set to none.

    {
        if(timeToFall < 0)
        {
            theCageRB.constraints = RigidbodyConstraints.None;
            Invoke("FreezeRB", .1f);
            Destroy(gameObject);
        }
    }
    void FreezeRB()
    {
        theCageRB.constraints = RigidbodyConstraints.FreezeRotation & RigidbodyConstraints.FreezePositionX
                & RigidbodyConstraints.FreezePositionZ;
    }```
leaden ice
#

also not sure I really understand what you're trying to do here

fiery path
#

wait ofc

#

yk what

#

Simply just a blind moment and Ive just done it

#

Thanks anyway

supple hinge
#

how do i name my script to other scripts?

#

like, if This Collides with this Script 001 is Disabled for X amount of time

solemn raven
#

how to add [Range(0,100) to a float's property ?
is it even possible ?


public float someFloat;
 [Range(0, 100)]
public float SomeFloat
    {
     get{ return someFloat;}
     set{ someFloat= value;}
    }
scenic creek
simple egret
#

Yeah, add the attribute to the field

#

You can also use an auto-property for that:

[field: Range(0, 100)]
public int SomeValue { get; set; }

field: tells the compiler to add the attribute to the auto-generated backing field

solemn raven
simple egret
#

You're not applying the attribute to a property

#

Properties have accessors { get; set; }, make sure you've put it on the right one

solemn raven
#

that is what I did


public float someFloat;
 [field: Range(0, 100)]
public float SomeFloat
    {
     get{ return someFloat;}
     set{ someFloat= value;}
    }
simple egret
#

Works fine for me

#

Ah, because it's not an auto-property

#

You have your own backing field declared. In this case just put the attribute on that, without the field qualifier

vagrant marsh
#

Does anyone know how to get ruletilemaps working easily for a 2D platformer
idk why but i find it confusing

fresh cosmos
#

im trying to write some code when a scene changes. but i am not getting EditorSceneManager.activeSceneChangedInEditMode to trigger. what exactly is it that triggers it?

grim pebble
#

Having a little trouble wrapping my head around what project on plane does with a direction thinkPeepo is this

// is this
_velocity = Vector3.ProjectOnPlane(_velocity, Vector3.up)

// the same as
_velocity.y = 0;
_velocity = _velocity.normalized;

simple egret
#

It basically flattens a vector on a specific plane

solemn raven
# simple egret Works fine for me

did u mean like my original code that didnt work ?
error :Attribute 'Range' is not valid on this declaration type. It is only valid on 'field' declarations.


public float someFloat;
 [Range(0, 100)]
public float SomeFloat
    {
     get{ return someFloat;}
     set{ someFloat= value;}
    }
simple egret
#

Yep, the same

grim pebble
#

Assuming _velocity is normalized when it starts out

#

Cool Okayge thanks

#

I found it in a component I wrote 2 years ago Aware

simple egret
#

Hm I don't think ProjectOnPlane normalizes though, you'd have to do it yourself

grim pebble
#

thinkPeepo Noted

simple egret
#

But it's really useful when the plane isn't flat on one axis. Say you want to flatten on your local up, whatever your rotation is

#

Go do that by modifying the velocity directly, good luck

solemn raven
simple egret
#

Something like this will do the trick

[Range(0, 100)]
public float _value;

public float Value
{
  get => _value;
  set => _value = value;
}
#

Ignore the contents of the property accessors, I made it shorter but your version with the return in the getter will work exactly the same

rugged goblet
#

There's no real reason for the field/property separation there, though, so it could all just be shortened to

[field: Range(0, 100]
public float Value {get; set;}
simple egret
#

Yeah exactly, just let the compiler do the work

solemn raven
# rugged goblet There's no real reason for the field/property separation there, though, so it co...

Thanks for example,
@simple egret thank you

Yes both of them worked smoothly <3, however, the desired result wasnt reached, I wanted to run a function when the value of float change by the editor, that is the whole reason of adding property to it in the first place, and the slider is just to make it look nicer.

I have noticed right now with or without the slider when I update the float value by the editor , the debug doesn't run.

public float someFloat;
 [Range(0, 100)] // with or without , it doesnt matter
public float SomeFloat
    {
     get{ Debug.Log("GET was fired"); return someFloat;}
     set{ Debug.Log("SET was fired"); someFloat= value;}
    }
simple egret
#

Yeah it bypasses the property

rugged goblet
#

Getters and setters won't be executed by the editor

simple egret
#

You can use OnValidate() message to do your validation in that

rugged goblet
#

The Unity editor is not aware of properties, only fields

solemn raven
proper pier
#

Anyone have any idea how its possible for the Raycast or spherecast to find a point here? Notes: swingsActive is a list containing two booleans. Predictionpoints is a list of two positions of sphere's which show possible locations to attach a grappling line to. Code: https://hastebin.com/share/efiqanifij.csharp
BTW: the anchor is not touching the ground, it's floating in the air. I tried codee-beginner before but it seemed like everyone was busy

#

I should note that the point aimers are facing in front of the player, who is facing the black columns

dusk apex
#

!code

#

Bot seems down.

grim pebble
#

Is it normal for "earth gravity" i.e. 9.8 meters/second to feel too low? Or is something wrong with how I'm calculating it? thinkPeepo I'm inclined to feel like I must be doing something wrong, but it's so simple...

            var verticalVelocity = _velocity.y;
            verticalVelocity -= (GravityDownForce * Time.deltaTime);
            verticalVelocity = Mathf.Min(verticalVelocity, -TerminalVelocity);
            _velocity = horizontalVelocity + (Vector3.up * verticalVelocity);

            _controller.Move(_velocity * Time.deltaTime);

Shrugeg
If I do 2x gravity (19.6m/s) it feels pretty much exactly how I'd expect thinkPeepo

#

Oh I just realized I'm doing terminal velocity wrong, but I don't think that matters here

#

๐Ÿ˜›

dusk apex
#

Log the velocity ๐Ÿคทโ€โ™‚๏ธ

grim pebble
#

Does that math look right? FeelsDankMan

#

Not a physics guy

dusk apex
#

Print the velocity..

grim pebble
#

HmmgeSit What am I looking for in the velocity specifically?

#

Like the physical experience of falling is a direct map of the velocity

dusk apex
#

See if it's what you're expecting.

grim pebble
#

I can tell from the fall that it is not, acceleration feels much too 'airy' like I'm in the moon, but I'm using the 'real world' gravity value thinkPeepo

#

But if I double gravity then it feels about perfect, which suggests my algorithm is wrong somehow... Thinkge

tawny elkBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

#
Visual Studio Code guide

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

https://on.unity.com/vscode

dusk apex
#

Bot is buggy

simple echo
#

hey guys ! I have an enemy who follows the pink player using AI pathfinding (A*). I used an A-star package but coded the AI. For the maze, I used 2D square walls. As shown in this video, the enemy takes a long time to find a path to the player. Can anyone check the code and let me know if there is anything got to do with the 2D square walls? Or is it something with the waypoints. The enemy goes ahead and then stops

pearl trench
#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

pearl trench
#

how do i unsubscribe from this?
playerInputs.movementActions.Reload.performed += ctx => Reload();

simple echo
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;

public class EnemyAI : MonoBehaviour
{
    public Transform player;
    public float speed = 200f;
    public float nextWaypointDistance = 3f; // Stores the next way-point distance

    Path path;
    int currentWaypoint = 0;
    bool reachedEnd = false;

    // Referencing the seeker script
    Seeker seeker;

    // Referencing the Rigid Body 2D script
    Rigidbody2D rigidBody;

    void Start()
    {
        // Finds the two components on the enemy object 
        seeker = GetComponent<Seeker>();
        rigidBody = GetComponent<Rigidbody2D>();

        InvokeRepeating("UpdatePath", 0f, .5f);
    }

    void UpdatePath()
    {
        if (seeker.IsDone()) // If it is not currently calculating a path
            seeker.StartPath(rigidBody.position, player.position, OnPathComplete);
    }

    void OnPathComplete(Path p)
    {
        if (!p.error)
        {
            path = p;
            currentWaypoint = 0; // Reset the current way point 
        }
    }

    void FixedUpdate()
    {
        // Checks if there is a path for the enemy to follow.
        if (path == null)
            return;

        // Checks if the enemy has reached the end of the path.
        if (currentWaypoint >= path.vectorPath.Count)
        {
            reachedEnd = true;
            return;
        }
        else
        {
            reachedEnd = false;
        }

        Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rigidBody.position).normalized;
        Vector2 force = speed * Time.deltaTime * direction;

        // Adding the force to the enemy
        rigidBody.AddForce(force);

        float distance = Vector2.Distance(rigidBody.position, path.vectorPath[currentWaypoint]);

        if (distance < nextWaypointDistance)
        {
            currentWaypoint++;
        }
    }
}
paper heart
#

how call material texture name in setTextureName in script? i tried the name how its in Editor ("Base") and in shaderfile ("_MainText") and for both it throws error "Material does not have texture property x"

solemn raven
#

hi ,
is it possible to make a float range with dynamic minimum and maximum ?

int min =0;
int max = 200; 
[Range(min,max)] // instead of [Range(0,200)]
public float value;
leaden ice
#

const int min =

#

So no not really "dynamic"

paper heart
#

no because it has to be outside declared function, and to have variable declared outside function it needs to be const
and const cant be changed during runtime

leaden ice
solemn raven
dusk apex
pearl trench
#

how do i do that?

dusk apex
pearl trench
#

I'm getting this error after destroying an object with this code
playerInputs.movementActions.Fire.performed += ctx => FirePerform();
i'm getting the error because i'm not unsubscribing before destroying the object right?

leaden ice
dusk apex
#

Likely so, else you're invoking while there are no actions subscribed (I don't recall the behavior of the New Input System off the top of my head)

pearl trench
dusk apex
nova python
#

why is started and performed almost instantly executed at the same time as each other, started always happens first but there's not even a single frame of time before performed is executed

#

it just means i cant run something between started and performed which is annoying

dusk apex
leaden ice
#

If you use a hold interaction for example you need to hold the button that much time before performed happens

nova python
#

wouldn't that work the same as cancelled?

#

or would performed still execute while you're still holding the button but slightly delayed?

leaden ice
#

The whole point of the hold interaction is that it performs after n seconds of holding

#

Canceled is when you release

dusk apex
pearl trench
#

thanks for your help man
but i think there's another reason why i'm getting the error
I tried that and the unsubscribe worked but still getting the error

proper pier
#

Anyone have any idea how its possible for the Raycast or spherecast to find a point floating in the air? Notes: swingsActive is a list containing two booleans. Predictionpoints is a list of two positions of sphere's which show possible locations to attach a grappling line to. Code: https://hastebin.com/share/efiqanifij.csharp
BTW: the anchor is not touching the ground, it's floating in the air, and the player is facing torwards those black columns.

hollow stone
proper pier
#

oh really? That would be very useful

#

wym submitting as a parameterr tho?

hollow stone
#

Debug.Log("Hit", gameObject);

#

If you do this, and submit the object you hit. You'll be able to click on the log in the output console and it will mark what you hit in the hierarchy.

nova python
#

Very confused, my jumpindex increases by 1 the first time I call Jump, but if I call jump again it wont increment? It'll increment again if I've called jump twice though

proper pier
#

how will it know what my hit gameObject is?

#

like where must I put it for it to know that

#

or is "Hit" built into raycast?

hollow stone
#

Your raycastHit structs has the information

hollow stone
proper pier
#

Sorry Mr. Jaws, I'm still a little confused. If I used gameObject in the debug, wouldn't it just give me the gameObject of whatever contains the script?

nova python
#

it doesn't increment the counter the second time I call it

#

but does it every other time

hollow stone
#

What do you mean call? Do you call it manually? Or do you mean when you're pressing a button?

nova python
#

pressing a button

hollow stone
#

So pressing the button twice does not produce two logs?

nova python
#

it does

#

but for some reason it just doesn't increment the second time I press it