#archived-code-general

1 messages · Page 318 of 1

heady iris
#

check if those methods are actually being called by adding a Debug.Log to each

candid coral
#

They are called indeed

heady iris
#

Are the methods being called the number of times you expect?

It looks like they're being called once as the objects become non-tracked, then again when they become tracked.

#

Moving the = true into Start would matter if the Default Observer Event Handler component was calling your methods before Start ran

#

which is possible

heady iris
#

Make sure you don't have multiple Object Rotation Manager components in your scene. That could produce confusing logs.

raven orbit
#

Does anyone know why rider generates seemingly weird markdown files?

candid coral
heady iris
#

so you have two Object Rotation Managers?

candid coral
#

One single script, but dragged to both of these

#

So both ImageTargets have that script

heady iris
#

Those are two completely unrelated components.

#

They don't know about each other.

#

Sounds like you want to have one object rotation manager.

candid coral
#

Probably. How do I create a single instace for both of them?

heady iris
#

by only having one component

candid coral
#

You mean, only setting one instance to one ImageTarget? And for the other imageTarget, try to access the instance of this one?

heady iris
#

No. Both of these "Default Observer Event Handler" components should be targeting the same "Object Rotation Manager" component.

#

One should be calling the SetCylinderInView method and the other should be setting SetCubeInView

heady iris
#

it calls the Cube method in one place and the Cylinder method in the other

candid coral
candid coral
#

But you are calling the class that way

#

So no functions can be called

heady iris
#

You have dragged in the script asset itself. Don't do that.

#

drag in the Object Rotation Manager component that's in your scene

candid coral
heady iris
#

The hierarchy displays all objects that are in the scene.

#

Where is your single Object Rotation Manager?

candid coral
candid coral
#

And only have the script in asssets

heady iris
#

It needs to be attached to an object in the hierarchy.

heady iris
candid coral
#

Oh, I get it now. So now that I have attached a single Object Rotation Manager, to the Cube ImageState for example, I can call its functions

#

But, how do I access to this one from the other ImageTarget (Cylinder one)

#

I hope I'm understanding it correctly

heady iris
# candid coral

just drag in the object with the "Object Rotation Manager" component on it

#

it can be from a different game object

candid coral
#

I have tried opening two tabs but they reference the same

knotty sun
#

you dont need to select the component, you can drag the game object that has the component on it and Unity will sort it out

heady iris
#

Drag the game object.

quiet ferry
#

public class BackgroundGen : MonoBehaviour
{
// distance for level to spawn from the player
private const float PlayerDist = 15f;

// object references
[SerializeField] private Transform Background1;
[SerializeField] private Transform BackgroundStart;
[SerializeField] private PlayerLogic player;

// the last end position of the most recent background to spawn
private Vector3 lastEndposition;

// gets player pos
public Vector3 GetPosition() { return transform.position; }

private void Awake()
{
    lastEndposition = BackgroundStart.Find("EndUp").position;
}

private void Update()
{
    if (Vector3.Distance(player.GetPosition(), lastEndposition) < PlayerDist)
    {
        // spawn BG part
        SpawnBGPart();
    }
}

private void SpawnBGPart()
{
    Transform lastBGPartTF = SpawnBackgroundPart(lastEndposition);
    lastEndposition = lastBGPartTF.Find("End").position;
}

private Transform SpawnBackgroundPart(Vector3 spawnPosition)
{
  Transform BackgroundTF = Instantiate(Background1, spawnPosition, Quaternion.identity);
    return BackgroundTF;
}

i got this code from an endless level tutorial as i thought it would work with backgrounds also. my goal is to have backgrounds spawn in all directions. when the player gets a set dist from the last endpoint. but i need it in all directions. how would i go about this. my idea is just to impliement the multiple end points? and ajust the code depending on which direction the player is travelling? but does anyone have any suggestions?

tawny elkBOT
quiet ferry
pliant spade
#

I have a problem with the assets bundle, When i want to create one I got this message:
Moving Temp/unitystream.unity3d to D:/<MyPath>/Assets/AssetBundles/base: Acces refused.

Why is that? I can't find anything online except this post:
https://issuetracker.unity3d.com/issues/building-an-asset-bundle-varient-results-in-an-error-when-there-are-identical-files-at-different-directory-levels

leaden ice
pliant spade
#

It's the unity application. The path it litteraly the project folder, if the unity app does not have access to it's own folder, what's going on

leaden ice
#

the unity app is not installed in your project folder

#

you may have put the project folder somewhere it doesn't have full access to

marsh prawn
#

Hey, can inherited functions use extra parameters or can they only use the parameter the base script has ?

leaden ice
#

You cannot change the signature of an overridden method

#

the signature has to match exactly

#

it wouldn't make any sense otherwise

#

how would you possibly call it?

marsh prawn
leaden ice
#

inheritance is so other things can call a polymorphic function on a reference of the parent type

marsh prawn
#

I Think i already know how do use it the way I want, so its alright, thanks for the answer and btw just answer the question instead of saying ''what you're saying does not make sense''

knotty sun
pliant spade
knotty sun
pliant spade
knotty sun
#

in general

pliant spade
#

I don't use it but i think it's enabled

knotty sun
#

then move your project to a path that OneDrive does not backup

pliant spade
#

Now it's in Documents, and onedrive does not seem to access it. And before it was in another drive and onedrive does not have access to it

knotty sun
#

Documents is backed up by OneDrive

pliant spade
#

It's still happening in another drive tho

knotty sun
#

external USB?

pliant spade
#

Nope

#

What do you mean? is it on an external usb?

knotty sun
#

so something like D:\Unity

pliant spade
#

Yea

knotty sun
#

but not on an external drive

pliant spade
#

On another internal drive

knotty sun
#

ok, make sure your path has no special characters, only A-Z and 0-9

pliant spade
#

Oh, it have - character

#

01-Documents

knotty sun
#

Unity can be real finiky about that

pliant spade
#

I'll try to move

#

Nope this time the path is D:/Work/Project/ and it's still say access refused

knotty sun
#

Have you tried building the bundle to a path outside the project path

pliant spade
#

I found the issue.

#

I'm building an asset bundle for a DLC, and i named the DLC folder "Base" for the default content. And my asset bundle name was "base", I think it was trying to overrite the folder or something like that.

knotty sun
#

Sounds about right
D:/<MyPath>/Assets/AssetBundles/Base/base

pliant spade
#

Well the bundle was created in AssetBundles path, so at the same level as Base folder

#

Now that this is solved, do you know if it's the right path to go for DLC?

knotty sun
#

sorry, no idea

pliant spade
#

No problem, thank you!

jolly stratus
#

guys, there is this dotnet folder in my C drive, program files. i was wondering can i just delete this one? it is of 7 gigs and i need some space in C, is this unity related at all? i downloaded android studio quite some time ago could it be because of that? i downloaded it to get the jdk sdk stuff for unity.

rigid island
#

but this seems to be runtime ? or is it sdk

#

I'm on mac so i forgot where windows saves it, ig Program Files makes sense

#

I dont recall that being 7gb tho

pulsar elm
#

7gb dotnet folder??

#

mine is only 740mb

#

but yes, it's important

#

but I do not understand as to how many things you got for dotnet that it's that large

somber nacelle
#

the size probably depends on what workloads and versions of dotnet they have installed. for example, mine is nearly 4gb

rigid island
#

dotnet --info (in terminal)

tall scroll
#

so @hidden compass is there a reason you use where T : Singleton<T> ? my monobehaviour one uses where T : MonoBehaviour
Also what's the benefit of making the class abstract again?

hidden compass
# tall scroll so <@317141358894645248> is there a reason you use `where T : Singleton<T>` ? my...

Using where T : MonoBehaviour allows any MonoBehaviour-based subclass to use the generic class, but it doesn't enforce the Singleton pattern. Without additional checks or logic, multiple instances of the subclass can be created, which goes against the Singleton pattern's intent of having only one instance.

Making the class abstract prevents it from being instantiated directly. This ensures that developers can't create an instance of the abstract class itself, but instead must inherit from it to create singleton instances. This helps enforce the intended usage of the class as a base for creating singleton instances.

tall scroll
#

will fix my stuff then

rocky basalt
#

I feel really dumb, but is there any common reason why the Transform point of child objects don't match the parent transform, even when their local positions are set to (0, 0, 0)?

In my inspector the childs are all zero local, but they're considerable off from the parent transform. I'm perplexed.

An artist I'm working with prob exported these from Blender, if that makes a difference

hidden compass
#

was my source.. and then i got some help from the beginner channel to help me refine it a bit

tall scroll
#

if the stuff you said didn't feel like it slightly defeated the point of a singleton I wouldn't fix it hehe

knotty sun
rocky basalt
hidden compass
#

its the origin of the mesh

knotty sun
tall scroll
#

(origin/pivot, meaning the specific place in the model that would be at 0,0,0)

knotty sun
#

yes

rocky basalt
#

ohh, so when they set it up in Blender, they did the work "away" from the center origin point?

zenith bear
#

Ok so whenever I try download the xr plugin management it’s always says there s an error so if someone could dm me thanks.

knotty sun
#

yes, they probably 'forgot' to apply the transforms when they exported

rocky basalt
#

thanks for this info. saved me some trouble

zenith bear
#

@knotty sun

#

May I help

knotty sun
#

May you help what?

hidden compass
clear umbra
#

Hey guys, I have this weird issue happening.

I was trying to change some of the quality settings of my mobile build of my game. Originally I changed the quality using Edit > Project Settings > Quality and then I changed the current quality to PC (from mobile)

However as soon as I did this I started having build problems on my physics device. In editor the game works fine, when I build for mobile (iOS) I just get a (somewhat) empty screen completely missing all my assets!

Things I Checked already:

  1. Added all scenes to build
  2. Rebuild the XCode project
  3. Close unity and re-open and then rebuild
  4. Changing quality back to mobile

I Really can't get this to build on my phone anymore when I litterally had it working a few hours ago losing my mind over this.

somber nacelle
#

this is a code channel

clear umbra
# clear umbra

interestingly it flashes pink when I try to load the game, and it shows my line renderer

clear umbra
somber nacelle
#

yes code-general. because this is a code channel

#

id:browse to find a channel relevant to your question

clear umbra
somber nacelle
#

please learn to read

clear umbra
#

compiling and building the project can be seen as "related to general coding concepts in unity"

somber nacelle
#

okay then show the code you are having trouble with

clear umbra
#

yeah dude if ur not gonna help, at least dont be toxic lmao

somber nacelle
#

my guy, you were the one arguing about where this question belongs. you should post it in the most relevant channel so you actually get help instead of posting in the wrong channel then bitching that it isn't actually the wrong channel because you didn't bother reading the full name of the channel or its description

rigid island
clear umbra
somber nacelle
#

well if you didn't post in the wrong channel, then share the code you are having trouble with

rigid island
naive swallow
tawny elkBOT
somber nacelle
#

that doesn't show any code

clear umbra
#

its almost like, u can have coding related issues

#

without the issue being in the code

somber nacelle
#

so then what code is that issue related to

#

hint: it isn't a code issue

clear umbra
#

Technically speaking: Unity C# Compiler Toolchain .NET

lean sail
#

lots of arguing that its relevant to the coding channel, but you called boxfriend toxic when he asked to see code.
There is both #💻┃unity-talk and #📱┃mobile

clear umbra
#

oyu can see plenty of people posting in this channel without having SPECIFIC code they are looking at

lean sail
#

so instead of arguing and wasting your own time, why not just post it in the correct channel? This is a waste of everyones time

naive swallow
# clear umbra without the issue being in the code

Well if literally anything made in code can be asked here I was wondering if anyone had any tips for beating Hecate in Hades II? I feel like I just literally don't have enough damage, like everything I do is barely making a dent. Do I just need more Arcana?

somber nacelle
clear umbra
rigid island
#

what is a toolchain issue?

clear umbra
#

not to mention the dude before me was asking about transforms and origins, I don't see how THATS a coding issue

rigid island
#

still confused on how changing quality settings would be affecting code at all

#

this seems related to asset database

#

I would first try to reimport all Library

clear umbra
clear umbra
rigid island
#

The Library folder holds all the cache/temp data

#

its in the project folder

quartz folio
lament mural
#

I'm trying to access the Music folder on my android device to see what files are in there but I can't seem to get it. Anyone know how?

rigid island
#

unity does let you call external plugins / code though, i bet you can access native kotlin code like that

lament mural
#

So I'd be relying on reflections?

rigid island
#

I suppose, how expensive can it be anyway? You'd only be getting some paths

hearty mortar
#

So I have a simple input buffering script for processing weapon inputs and handling multi-button chords. It's giving me a NullReferenceException and I don't understand why.

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

public class CombatInputBuffer : MonoBehaviour
{
  [SerializeField][Range(0, 1)] private double _chordingTimeout = 0.01;
  [SerializeField][Range(0, 1)] private double _bufferTimeout = 0.1;

  private double _chordingTimer = 0;
  private double _bufferTimer = 0;

  private List<InputAction> _bufferedInput;
  public IReadOnlyList<InputAction> BufferedInput => _bufferedInput;
  private bool _isChording = false;

  void FixedUpdate()
  {
    _chordingTimer -= Time.deltaTime;
    _bufferTimer -= Time.deltaTime;

    if (_isChording && _chordingTimer <= 0)
    {
      CommitChord();
    }

    if (_bufferedInput != null && _bufferTimer <= 0)
    {
      _bufferedInput = null;
    }
  }

  private void CommitChord()
  {
    _isChording = false;
    _bufferTimer = _bufferTimeout;

    Debug.Log("Inputs: "
      + (from action in _bufferedInput select action.name)
        .Aggregate((a, b) => a + ", " + b));
  }

  public void OnInputReceived(InputAction.CallbackContext context)
  {

    if (context.performed)
    {
      if (!_isChording)
      {
        _bufferedInput = new List<InputAction>();
        _chordingTimer = _chordingTimeout;
        _isChording = true;
      }

      if (!_bufferedInput.Contains(context.action))
      {
        _bufferedInput.Add(context.action);
      }
    }
    else if (_isChording
      && context.canceled
      && _bufferedInput.Contains(context.action))
    {
      CommitChord();
    }
  }
}
#

NullReferenceException is on _bufferedInput

#

Yet, as far as I can tell, the following intended invariants do seem to be true everywhere which should prevent that:

  • _bufferedInput is only ever accessed by the code when _isChording is true.
  • When _isChording is set to true, _bufferedInput is initialized to an empty list.
  • _bufferedInput is cleared to null on a timer which is longer than the one which sets _isChording to false
lean sail
#

Did you write this code yourself? Throw a debug in that if (!_isChording) and see if its ever even running. Thats the only area where I see you assign something so it wouldnt be null

hearty mortar
lean sail
#

well first thing is you should specify what line the error is actually happening on, the stack trace of it in unity should also tell you when its being called as well. Though really its probably just that _isChording isnt what you think it is at a certain point.

hearty mortar
#

It's happening on the Debug.Log line (actually an ArgumentNullException, but same thing), and at the contains checks in OnInputReceived

flint shore
#

FixedUpdate is not Update, I haven't trawled your code in detail but are you sure things are being called in the order you expect?

Why not attach the debugger and see...

somber nacelle
#

honestly why even bother creating new instances of the list? just clear the list when you need it to be empty and reuse the same instance

flint shore
lean sail
#

i have trouble following this code, but it looks like theres just some random and independent logic happening between the chords and the buffered input. the bufferedInput can just be independently set to null from fixedupdate without care about anything else. then nothings really stopping an NRE from happening like anywhere else

#

you could also do what boxfriend said, but i suspect theres more issues than just null here. Like it'll probably not be using the correct values if theres already this issue

hearty mortar
#

... At least, that should be the case, but I added an assertion to that and it's not.

lean sail
#

well its clear that theres an error, where it is null when it shouldnt be. what you wrote is what you assume is happening, the debugger or just simple logs should point you in the right direction

hearty mortar
#

Oh

#

Doh

flint shore
#

I mean its a fun thought activity to solve the logic error by thinking but if you actually want to fix your problem attach the debugger set the break points and see what is actually happening.

hearty mortar
#

I'm stupid

#

I forgot to initialize the buffer timer

#

Or rather, I for some reason initialized it at the end of a chord, not the start

hearty mortar
#

Ok, I'm confused now. Everything here should be happening in one thread, right? No concurrency?

#

(NullReferenceException is fixed, but I'm running into a different issue now)

somber nacelle
#

yes, unless you specifically do any multithreading yourself there will not be any multithreading happening on your monobehaviours. and unity messages like FixedUpdate will never be multithreaded

hearty mortar
#
    private void CommitChord()
    {
        Debug.Assert(_bufferedInput != null || !_isChording);
        Debug.Assert(_isChording);

        _isChording = false;

        Debug.Log("Inputs: "
            + (from action in _bufferedInput select action.name)
                .Aggregate((a, b) => a + ", " + b));
    }

How is this getting called twice without that Assertion failing???

flint shore
#

if only someone mentioned using a debugger ...

hearty mortar
#

Ah, correction, the question is "how is the performed event happening twice for a single button press?"

cosmic rain
flint shore
#

A tool that lets you see exactly what gets called when... and the (stack) history of what called it ...

#

🙂

cosmic rain
hearty mortar
flint shore
#

Are you sure they are all pointing to the right object?

hearty mortar
#

Yeah, but moreover, it's only getting called twice for "Performed"

#

Not for "Canceled"

flint shore
#

So step through the darn thing...

cosmic rain
hearty mortar
flint shore
#

That's not stepping through with a debugger.

hearty mortar
cosmic rain
lean sail
#

you are also calling that functions from other areas like fixed update. this whole thing seems like spaghetti

cosmic rain
flint shore
#

Lots of options here.

#

Learning how to use the debugger properly is way more important to your success than solving this one logic error, seems like a good time to do so ... two birds with one stone and all that.

#

(and yes I know some people go their entire career without using debuggers, but it is the best tool for many jobs, this seems like one of them)

hearty mortar
flint shore
#

you do? 😛

#

If you have the call stack of whats calling the code you don't expect to be called, its very very likely its going to tell you more than you know now.

lean sail
#

hell, even the stack trace alone from the debug.log should tell you

hearty mortar
flint shore
#

But set break points on the thing called twice and the place that the flag changes.

hearty mortar
# lean sail hell, even the stack trace alone from the debug.log should tell you

Stack trace is identical for both, running off into Unity native immediately

Processing: Weapon 1, Performed
UnityEngine.Debug:Log (object)
CombatInputBuffer:OnInputReceived (UnityEngine.InputSystem.InputAction/CallbackContext) (at Assets/CombatInputBuffer.cs:52)
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr) (at /Users/bokken/build/output/unity/unity/Modules/Input/Private/Input.cs:120)
flint shore
#

You can see which bit is happening out of the order you expect, or you can see if you 've got something being called twice you don't expect to be, the point being it will probably tell you something about what is happening.

hearty mortar
#

Like, the key thing I don't understand is, how can I get two performed triggers but only one canceled?

#

I thought the two have to occur in pairs?

#

I mean, one is button down, the other is button up?

cosmic rain
lean sail
#

did you subscribe the event in code ever?

hearty mortar
#

... It's because I set the button to "PressAndRelease" thinking that that was necessary to send both button down and up

lean sail
#

like some ctx.performed += ...

flint shore
#

Event that is triggered when the action has been started but then canceled before being fully performed.

hearty mortar
#

The Player Input stuff

flint shore
#

So it is certainly possible to have more performs than cancels.

hearty mortar
#

That said, I think I solved it

flint shore
#

start leads to perform or cancel

hearty mortar
#

TBH, I'm having trouble wrapping my head around the new input system in general. I'm half tempted to just use the old functions for listening to the hardware more directly

#

But I figure it's important to get this stuff down

flint shore
#

If using the new system you should probably write your own interaction to handle buffering.

flint shore
#

Implement IInputInteraction to make your buffering part of the system rather than something that sits outside of the system.

#

I'm guessing at the context of your game, but it seems like what you would want to do is send Performed at the right time.

#

So your buffer is effectively a custom interactions that knows when a button is down (probably sending Start on press), and if it falls in the allowable buffer/window it sends Performed at the right time (or Cancel if the buffer expires).

hearty mortar
#

So, for starters, I'm trying to set it up so chords can be processed, e.g. pressing A + B at the same time

#

Also input buffering for chaining attacks, so if you press a button before the cancel window of the attack begins, that input is still around, but that I don't think I can implement within the new input system

#

I would love it if there's some way to implement the chording within it

flint shore
#

Hmm maybe not ideal then, a fighter probably has too much nuance in the control.

#

At some level of complexity you would be fighting the system rather than gaining from it.

hearty mortar
#

Not actually a fighting game lol, but yeah fighting game style controls. It's a Monster Hunter clone

flint shore
#

Our designers want to take our battles along that Monster Hunter route, I prefer the current system (which is kind of a simple combat which then leads you to an Auto Battler). Reflexes not my thing.

#

Anyway off topic!

hearty mortar
#

FSM is going to be fun to implement haha. I'm still debating between defining the structure in code or implementing a Graph Tools UI

flint shore
#

Not sure if XNode is still maintained but it was a nice API for very quickly and easily creating custom tree like structure in editor.

hearty mortar
# flint shore Not sure if XNode is still maintained but it was a nice API for very quickly and...

Unfortunately looks like no. There is this from Unity themselves: https://github.com/needle-mirror/com.unity.graphtools.foundation/blob/master/README.md

GitHub

A framework for node based tools including a graph data model, a UI foundation and graph-to-asset pipeline. Use this package to speed up the development of graph based tools for the Unity Editor th...

#

But it also hasn't been updated in 3 years and is still in preview

gray mural
#

I wouldn't consider this a newbie question. I suppose, this may be achievable by first selecting the InputField's Selectable, then activating the InputField itself. I'm not sure and you gotta check it out.

inputField.Select();
inputField.ActivateInputField();
jolly stratus
merry stream
#

anyone know why there is a big delay with my inputs when pressing two different keys? Say I try to press the key 2 and key 3 ability together, only one will trigger. https://gdl.space/opuwitesor.cs

restive ridge
#

I'm making a 3D isometric style game, made pretty much the basic character controller however since the game is isometric, my camera is rotated 45 degrees on the Y, so the player is always moving 45 degrees to the left (45 degrees north west of the camera you could say) how do i make it that when i press W the player moves directly forward of the camera? Code: https://gist.github.com/Winter-r/c023d12a56575925d9a6f3270f92c49a

gray mural
#

Also, this doesn't make sense. The Action cannot be unsubscribed like like.

abilityAction.action.performed -= ctx =>
    TryUseSkill(Array.IndexOf(
    abilityAction.action.controls.ToArray(), ctx.control));
#

So have a method which does what you do when subscribing and unsubscribing it

#

And this is a List, right?

abilityAction.action.controls
#

You may use the List.IndexOf(this) method instead of the Array.IndexOf

gray mural
#

Do it also include rotating the player?

fathom finch
#

Hey guys, I have a script with one function like so:

public IEnumerator Shoot() {
        //If trajectory is even possible, then create the projectile object and apply said trajectory.
        if(GetTrajectory(out Vector2 velocity)) {
            GameObject pj = Instantiate(projectile, transform.position, new Quaternion(0.0f, 0.0f, 0.0f, 0.0f));
            pj.GetComponent<FlyingEnemyBulletBehavior>().parent_flying_enemy_ref = this.gameObject;
            pj.GetComponent<Rigidbody2D>().AddForce(velocity, ForceMode2D.Impulse);
        }
        yield return new WaitForSeconds(launch_rate_seconds);
        has_shot = false;
    }```
#

Im trying to set a public variable "parent_flying_enemy_ref" inside a script called "FlyingEnemyBulletBehavior", that belongs to the instantiated GameObject variable "pj", via the current script that this function resides in^

#

for some reason the line

 pj.GetComponent<FlyingEnemyBulletBehavior>().parent_flying_enemy_ref = this.gameObject;

causes the rest of the function to not function

#

does anyone know why? if I need to provide more code let me know

#

removing that one line I talked about makes the function work again

mellow sigil
#

In what way does it not work exactly?

fathom finch
#

basically the function spawns a projectile gameobject, which is just a ball, and launches it with a specific velocity

#

normally this function does exactly that, but with the addition of the line I spoke of, it doesnt create projectile gameobjects and launch them anymore, nothing happens

mellow sigil
#

Add logs after the line to confirm that the code runs, and make sure errors aren't disabled in the console

fathom finch
#

it doesnt, I tried the logs approach

#

nothing printed

#

nothing before as well

#

which is quite confusing

mellow sigil
#

And the logs print if you remove the line?

fathom finch
#

yes, and the function works as expected

mellow sigil
#

Show the FlyingEnemyBulletBehavior script. !code

tawny elkBOT
fathom finch
#

one sec

merry stream
# gray mural Also, this doesn't make sense. The `Action` cannot be unsubscribed like like. ``...

the cool down is handled separately, I was talking about the actual key presses from the input system. I had the action map set as button instead of value which was causing the issue. However when I press both keys at the exact same time, only one is registered still. is that a limitation with the input system or am I doing something wrong. I have my action map Skills with binds for 1, 2, 3 etc. Also, I assumed that's how you subscribe for the triggered event, am I mistaken? it works perfectly fine

fathom finch
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlyingEnemyBulletBehavior : MonoBehaviour
{

    public GameObject parent_flying_enemy_ref = null;
    private Rigidbody rb = null;
    private Collider2D col = null; 

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        col = GetComponent<CircleCollider2D>();
    }

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

@mellow sigil

knotty sun
fathom finch
#

ah my mistake

#

forgot to add the 2D for the rigidbody

#

but that wouldnt be the issue would it?

mellow sigil
#

Can you show a screenshot of the full console? There should be at least a warning about the invalid quaternion

fathom finch
#

one sec

#

🗿

#

i didnt even attach the script

#

that im trying to call

#

thats why it wasnt working @mellow sigil

gray mural
mellow sigil
#

So did you have errors hidden or why didn't you see the NRE error?

fathom finch
#

😔

#

silly old me

#

thank you for helping though

boreal condor
#

hey there I'm wondering if anyone can help me think a solution for dragging a rigidbody from a pivot point instead of its center, my method works but positions are kinda odd when the object rotates, I need a second brain im almost suffering
Here's some relevant code

// This line is inside a method
_grabbingBody.AddForceAtPosition(
                GrabDirectionTowardsCursor() * grabForceMultiplier,
                GrabPointTransformed()
            );
// ===================== FUNCTIONS & HELPERS ============================
public Vector2 GrabPointTransformed()
{
    return _grabbingBody.transform.position + _grabbingBody.transform.TransformDirection(_objectGrabPointPivot);
}

public Vector2 GrabDirectionTowardsCursor()
{
    return (PlayerCursorAttachment.CursorPosition() - GrabPointTransformed());
}
// This is what I do when left click is pressed, CursorPosition() is the position of the yellow eye sprite (which is another GameObject that acts as a cursor)
_objectGrabPointPivot = PlayerCursorAttachment.CursorPosition() - _grabbingBody.position;
_initialGrabPoint = PlayerCursorAttachment.CursorPosition();
latent latch
#

Maybe use transform point then make a direction using world coordinates?

#

Actually, I don't think you need local coordinates. Just a position here with world coordinates

boreal condor
#

I'm actually confused about how AddForceAtPosition handles the given position

#

I'll read the docs maybe I missed something

latent latch
#

I assume the problem is the arm is going further from the point you clicked, right?

#

So the question is, does the location you click give the correct coordinates or is it another issue because I'm not too sure of the requirements here.

boreal condor
boreal condor
latent latch
#

TransformDirection and TransformPoint deals with local position such that the object is a child to another, and you want to convert the local position relative to the parent as world coordinates

boreal condor
#

the hand is only visual, it moves to where the resulting position is, pretty much the offset between the box and the click

latent latch
#

Ah, actually maybe im confusing myself. You would just grab the local coordinates via transform.local otherwise, so the method is useful to get relative coordinates without having them actually be child/parent.

#
    void Start()
    {
        // Instantiate an object to the right of the current object
        thePosition = transform.TransformPoint(Vector3.right * 2);
        Instantiate(someObject, thePosition, someObject.transform.rotation);
    }

Right, so say you want to always get a unit that's always on the right side of the object, you could use this method.

#

and you have InverseTransformPoint where you can get the exact local* coordinates of that position in space that's relative to another transform without having to child it.

boreal condor
#

TransformPoint is the equivalent to what I was doing before?
_grabbingBody.transform.position + _grabbingBody.transform.TransformDirection(_objectGrabPointPivot)

latent latch
#

what space is _objectGrabPointPivot in?

boreal condor
#

wdym by space?

latent latch
#

wait, you're using TransformDirection here with a position vector

boreal condor
#

yeah, that position is the pivot from where I want to drag, I'm making small changes to see what improves its behaviour

latent latch
#

is playercursorattachment using ScreenToWorld?

boreal condor
#

No

latent latch
#

What's the returned value of it then?

boreal condor
#

the objects position lol

#
    public static Vector2 CursorPosition()
    {
        return Instance.cursorTarget.position;
    }

Im not using positions provided by the mouse

#

so the cursor pretty much lives in the game's world

latent latch
#

I'm trying to figure out why you don't just use world positions for everything. Wherever this cursor is, just grab the transform.position, and if you need a direction from the target (cursor position) minus the player position

boreal condor
#

I need to somehow keep _objectGrabPivotPoint attached to the objects rotation AFTER it has been grabbed, but otherwise use the cursor position no matter the rotation, I am not sure why am I failing on that last step

latent latch
#

Oh, but the hand sticks to the point of the object, so there is some locality with the object going on i guess.

boreal condor
#

My math is most likely wrong but unsure where

latent latch
#

It makes sence of what you're trying to do because you are holding onto that item without childing the hand to the object, so yeah these methods would be helpful.

#

So the problem here is where you click, you want to cache a local point onto that object you are holding.

boreal condor
#

the red line represents the correct place where I want to drag from, so perhaps I'm doing wrong modifications to _objectGrabPointPivot after it has been set with the correct values

latent latch
#

world position to local relative to the box's position

boreal condor
#

tried using it and made everything fly, I'll read what it does exactly

#

how would you use it?

latent latch
#

boxTransform.InverseTransformPosition(cursorWorldPosition)

#

this would give you the local point on the box from where you click

boreal condor
latent latch
boreal condor
#

oops i used the wrong method my bad

latent latch
#

so basically, cache the point when you click, and every frame afterwards if you want the hand to go to that position (or using some force method). You would use boxTransform.TransformPoint(cacheLocalPosition) to get a world point

#

so now you can devise a direction such that:
boxPointWorldPosition - handWorldPosition = direction

boreal condor
#

transformpoint behaves exactly as my previous method so, good thing I learned about this one at least yet the issue regarding the box rotation is still present, I'll turn it into a sprite with visible directions maybe it helps a little more

novel bough
#

@fervent furnace thanks for your wonderful explanation, I saw that you've been typing for so long!😇

latent latch
#

transform.TransformDirection is useful too, but what I can make out of your code is you're using a point for the parameters when it expects a direction

#

or maybe I am misunderstanding what that variable may be

normal wharf
#

I'm struggling to design how I want to handle data exactly in my project. I'm trying to design a simple RPG skillset, and this is what I've come up with so far:
A MasterAttribute script, which I then generate gameobjects off, for the actual skills, they look like the attached pic.
A manager script to create a defined sized array, then populate it

What I'm confused about is; In my own design I don't know how you would interact with the gameobjects (the attributes), but also with a player + enemies, how would I manage their attributes as well, seperately?

I am trying to plan a modular system that could be used for various data like currencies, stats, etc that can be extended in the specific items if needed.
Image

#

Just looking for advice, this seems like a bad approach, but everything else I've seen is too simple, or hard coded...

latent latch
boreal condor
latent latch
#

now, pass that point back into TransformPoint and do the same method of debugging similarly, but this time you should get a world position which is always the same

boreal condor
#

so what I'm understanding by changing the sprite is that it attempts to use the world Y position as the object's Y relative position

latent latch
#

what's happening here is that when you click the left of the box in world coordinates, it's translating to left of the box in its local coordinates

boreal condor
#

yeah its pretty much expected, howeverrr using global coordinates directly causes conflicts, i'll do changes and show what happens exactly

latent latch
#

using inversePosition, this position in world coordinates should always become a position in local coordinates as to where you click

latent latch
normal wharf
#

It just seemed like that would be a more robust system (Which I'd like to design)

latent latch
boreal condor
#

Dragging rigidbody from Point

normal wharf
#

That IS something I'd like to do, e.g. weapon type, armour type etc.

#

But I realised my base design is too pidgeon holed, I just don't know what a good way of doing it is, am open to suggestions 😦

latent latch
#

I've made stat systems such that if they are a caster then they have stats related to casting. They have spell damage, Mana, spell range, ect. But, when it comes to base stats like defenses, usually all my entities had it.

#

Interfaces like ICaster, IMelee, IRanger

#

otherwise I'd just give everything stats so I wouldn't have to fallback onto scenarios where they didn't have stats to compare against.

normal wharf
#

I did think interfacing might be a good way to handle it, but would you just have a script for each stat, and then that manages interactions that way?

#

Also; How do you assign that status to say, an entity? With a manager script

This is where my understanding is failing I think

#

The data structures i'm fine with, I just don't even have examples of these interacting with eachother

latent latch
#

Well, first off I'd make an SO for each enemy and assign what they can do. Your method with this design would be composed of a list of stats each of these entities would have. My method of grouping stats a bit more would be a few fields that detail that if they are a caster I would assign a struct/class of stats relating to that.

#
[Flags]
public enum Affinities
{
    None = 0,
    Caster = 1 << 0,
    Melee = 1 << 1,
    Ranger = 1 << 2,
}

public class EnemySO : EntitySO
{
  [field: SerializeField] public Affinities Affinities {get; private set;}
  [field: SerializeField] public BaseStats BaseStats {get; private set;}

  //Offensive Stats
  [field: SerializeField] public CasterStats CasterStats {get; private set;}
  [field: SerializeField] public MeleeStats MeleeStats {get; private set;}
  [field: SerializeField] public RangeStats RangeStats {get; private set;}
}```
normal wharf
#

Ah, I see

#

Each of these being their own script with itneraction code, like you mentioned right?

#

Or are they lists which you set in each entity? because isn't that frequently re-used, even if just interfaces?

latent latch
#
[Serializable]
public class CasterStats
{
  public float SpellDamage;
  public float CastSpeed;
  public float Mana;
}```
#

Ah, I was going to suggest to check if these classes are null, but Unity will always create them regardless if you edit their instance in the editor, so what you can do is have flags or my preferred way of doing it with a flag enum

normal wharf
#

Gotcha, thanks for the examples!!

#

This gives me a few ideas 🙂

latent latch
#
[Flags]
public enum EntityAffinities
{
    None = 0,
    Caster = 1 << 0,
    Melee = 1 << 1,
    Ranger = 1 << 2,
}```
#
if(EnemySO.EntityAffinities.HasFlag(EntityAffinities.Caster))
#

There is support for them in the inspector which is surprising.

normal wharf
#

Flags? Very cool

placid summit
#

Maths question - has anyone done ellipse to ellipse intersection tests?! I am struggling to find C# code, I could use a general intersection maths library

vagrant blade
fervent furnace
placid summit
placid summit
#

but converting equations to C# is a problem for me!

#

hmm seems an n sided polygon might be the reasonable maths fix rather than such accuracy

tight goblet
#

Hey there mates, Im trying to cull particle system when offscreen, all is setup as recommended, but still not working (the PS still running even when cam is not showing the object):

late lion
magic harness
#

Hey guys, quick question. I'm using the navmesh system to move my player, and i did the boot logic for my game in a way where i create my player in a different scene from where my gameplay actually happens.

So.. there is no navmesh whenever i create my PlayerCharacter, how can i go around that problem?

tight goblet
late lion
late lion
# tight goblet through script and log?

If you have a particle system that is a burst emission that goes off every 5 seconds, and you look away right as a burst starts, wait 2 seconds and then look back, you should see that the same burst is still finishing, even though it should have finished in those 2 seconds.

tight goblet
tight goblet
late lion
tight goblet
#

When it is doing culling, it doesnt pauses the ps ?

I did that:

if (_particleSystemOne.isPlaying)
{
    Debug.Log(gameObject.transform.parent +" - "+ _particleSystemOne + " - is playing");
}
#

there is a way to check if culling is working through script?

late lion
#

You can check if the renderer is visible through ParticleSystemRenderer.isVisible. Or you can check if ParticleSystem.time is still increasing. If you have the culling mode set to Pause, the time should stop. If it's set to PauseAndCatchup, it might either just keep going or pause and then jump when visible again.

kindred vessel
#

Hello!

I have a base abstract class Fruit.
I have children classes, Apple, Banana and Orange, each with different parameters to change.

I want an editor that can select one of the children classes of Banana from a dropdown and use that class's field editor.

For example, I have a List<Fruit> fruits, and in the editor I add a new element. It shows a dropdown, and once I select class Banana, it allows me to change the parameters of that Bananaobject; when I find it on the code, I can cast that Fruit object to Banana and use its parameters.

How would I do this?

grand frost
kindred vessel
#

I'll ask there. Thanks!

kindred otter
candid elm
#

do you guys use chatgpt as aid

heady iris
#

no

candid elm
#

im having an issue in my prototype

where animations for my player stay stuck in idle when looking at a large crowd of enemies

#

sorry if this is not the appropriate channel as the issue is not code related, but in the footage you can see stutters in the animation that happens when you look towards a large crowd of enemies (there are many more enemies hidden behind the wall)

#

if i look at them the animation gets stuck to idle

leaden ice
#

the player's?

candid elm
candid elm
hardy barn
#

any1 know what is the error in the "get"?

leaden ice
#

look at the other ones and compare.

#

Just an unrelated FYI C# convention is for your type names (e.g. tile and tillcell should typically be PascalCase, not lowercase)

candid elm
#

uhhh
how do you paste code in discord and make it look like actual code if u get what i mean

tawny elkBOT
candid elm
#
  public void test();
#

thx

jagged hedge
#

I want to make an input record/replay system. Two questions:

  1. Can I simply use Update() to record/replay the inputs? Or would that cause issues because Update() is framerate-dependant?
  2. Is the Physics engine 100% deterministic? Or is there also some framerate-dependancy?
hardy barn
#

any1 know what is the problom?
error show
Suppression State
Error CS1061 'tillcell' does not contain a definition for 'coordinates' and no accessible extension method 'coordinates' accepting a first argument of type 'tillcell' could be found (are you missing a using directive or an assembly reference?)

leaden ice
vast patrol
#

ok i will try to do this once more

leaden ice
vast patrol
#

how do i generate vector points for bezier curves

candid elm
#

Hi im having an issue with my interactoruimanager class which basically manages the interface that allows u to interact with nearby interactable objects, the issue is that, the function executes fine and well, except that the SetActive part

it only works when theres an interactable within range but in this context it doesnt for some reason


public void PopUpTheInteractorUI(Vector3 position, string name, string type)
{
    Debug.Log("trying to pop");
   /* This is so that this function doesnt get called more than once after     being called since its actively being called by an update function in      another script that only activates when an interactable object is near     the player
   */

    if (hasPoppedUp) 
    {
        Debug.Log("pop fail");
        return;
    }

    hasPoppedUp = true;   
    
    /* the interactor is a class that i made which is basically a canvas       in world space that acts as an interact interface and appears above        item near to player
    */ 
    interactor.gameObject.SetActive(true);

    // position works fine, but for somereason, the interactor doesnt          activate
    interactor.gameObject.transform.position = position;
    interactor.SetPopupInfo(name, type);
    Debug.Log("pop success");

}


vast patrol
#

own code only no libraries

candid elm
#

everything works

#

except the setactive part

rigid island
#

so its staying inactive ?

candid elm
#

yes

rigid island
#

are you positive interactor isn't changed to inactive anywhere else

candid elm
#

if theres no interactable

rigid island
candid elm
#

it deactivates

candid elm
hardy barn
#

Any1 know what is the problom?
sry for too much probloms

candid elm
rigid island
leaden ice
hardy barn
#

Cannot implicitly convert type 'tile' to 'Tile'

#

but will figure it out thanks

rigid island
#

seems you're mixing a custom Tile with Unity's Tile

leaden ice
#

Looks like tileprefab is tile but you're trying to put it in a Tile variable

candid elm
leaden ice
hardy barn
#

ye ye

#

thanks

rigid island
candid elm
#

would doing some async magic solve things

#

if i manually activate the interactable then walk away, it naturally fades away

#

the fade away works

#

just not the appearing

rigid island
#

the fact that its in Update is a little worrysome

candid elm
#

idk how to do it otherwise

rigid island
#

code doesn't lie, if its staying inactive it is constantly setting to active-false

candid elm
rigid island
candid elm
#

first pic is how to find the closest interactable

rigid island
candid elm
candid elm
#

ill try doing async black magic otherwise

rigid island
#

don't think async would change much here except add more complexity where it doesn't need to be

candid elm
#

btw theres a single bool controlling the popup in the interact ui class

#

if object is activated once
bool becomes true
cant activate again

rigid island
#

you need to find the condition to reset the whole system, I usually do a raycast so typically in the else statement is where I put it, but since here its a distance check its a bit more tricky

candid elm
#

only by disabling the ui can you reactivate

candid elm
vast patrol
#

woah that image already tells everything about curves

rigid island
vast patrol
#

just increasing point on first line and second line by same % right

candid elm
rigid island
#

like here

#

I see you tried something like that here already

rigid island
#

what was wrong with it

candid elm
#

i forgor

rigid island
#

just make sure you check if interactor is not null

candid elm
#

ill try tweaking it

candid elm
#

so everything below that line of code is the else statement basically

rigid island
#

dont need to exit the whole thing, just the part of the UI. the return is fine, just put FadeOut inside the if interactor is not nulll

vague surge
#

Not sure if this question should be here or in #archived-code-advanced,
I have a modual avatar that i'm merging at runtime into a singular skinned mesh. the outcome mesh looks fine but it does not render in unity.
what would be your starting point to investigate the issue? I am starting from a new mesh() so i might be missing some default setting

rigid island
#

the Popup right?

candid elm
#

yes

rigid island
#

yea DeactiveInteractorUI

candid elm
#

if i deactivate all codes for the fadeout

#

the appear works again

#

lol

#

but i dont know where the contradiction in my code is

rigid island
#

probably

candid elm
rigid island
#

just remove it

#

call it manually if the count ==0 && is active

hardy barn
#

tried fix that

candid elm
hardy barn
#

i cant

candid elm
#

if its inside a method thats called in update

rigid island
#

thats why Im saying remove it from Update you dont need it

hardy barn
#

all the code
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UIElements;

public class Tile : MonoBehaviour
{
public Tile state {get; private set;}

public tillcell cell {get; private set;}

public int number {get; private set; }

private Image background;

private TextMeshProUGUI text;

private void Awake()
{
    background = GetComponent<Image>();
    text = GetComponent<TextMeshProUGUI>();

}
public void Setstate( Tilestate state , int number)
{
    this.state = state;
    this.number = number;

}

}

tilestate CLASS

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "tile")]

public class Tilestate : ScriptableObject
{
public Color backroundcolor;

public Color textColor;

}

leaden ice
candid elm
rigid island
#

its confusing you and your IDE (code editor)

hardy barn
#

ye ye

#

so change class names

leaden ice
hardy barn
#

have no idea how to fix that

#

im dumb af

#

idk

candid elm
#

knowing if the count is 0 would require an update wont it?

rigid island
#

but ideally you would only run it once, since you only have closestInteractor once

candid elm
rigid island
#

also. you should store these inside a variable, especially if you need to use it more than once

leaden ice
#

you're overcomplicating it. @hardy barn

You have:

B thing = whatever;
A otherThing = thing;```
You can't store a B in an A variable.
You would need:
```cs
B thing = whatever;
B otherThing = thing;```
vast patrol
#

no wait also curved line goes under the percentage

rigid island
#

so you're only fading if its not null and count is 0

candid elm
rigid island
#

since it occurs every frame and == 0

candid elm
#

my naming convention is kinda bad

rigid island
#

thats not what pops the UI ?

candid elm
#

the UI itself is a singleton instance

candid elm
rigid island
#

those are the ones not popping up because ur hiding the UI everyframe

#

did i understand that?

candid elm
#

ill do a little tweak brb

rigid island
#

oh now Im confused so thats working fine?

#

but what isn't

candid elm
#

thats the only issue

#

it doesnt fade in technically it just gets set active

#

i plan to tween it when it actually works

rigid island
#

ok but its not being active because the setting to active false is running every frame yes?

#

so the problem is SetActive(false) running everyframe

candid elm
candid elm
#

and the debug logs prove that

#

my theory is that the update is so fast that it gets triggered before the first check idk

rigid island
#

quite possibly

candid elm
#

this is why im thinking of using an async method

#

that waits after the distance check to execute the second method of showing the ui

#

@rigid islandnvm i fixed it

#

literally all i did

#

was remove 1 bool

#

LOL

rigid island
#

which one is that

#

was just typing something about it

#

curious if it was related

candid elm
candid elm
#

i didnt want the tween to be called more than once

#

as u can see in the commented tween part

#

this is a nightmare for me

rigid island
#

ohhh

candid elm
#

do u know how to properly do it with tweening

rigid island
#

you're talking about DOMove part?

candid elm
rigid island
#

You could potential make a bool that gets back to false when the tween is comeplete

#

kinda how you had it before commenting

candid elm
rigid island
#

the OnComplete part

candid elm
#

oops

rigid island
#

shouldn't that be !haspoppedUp

candid elm
#

its supposed to be if (!haspoppedup)

candid elm
candid elm
rigid island
#

distance check conditions?

candid elm
#

nvm im stupid

rigid island
#

what was it ?

candid elm
candid elm
#

and i accidentaly crashed my unity trying to fix with a while loop

#

wild

rigid island
candid elm
#

tweening is the most rage inducing thing 4 me

inland pawn
#

Hello! I'm having some problems with a glitchy rigidbody that I'm trying to move... It's like jittering everytime move the player, altrough the player doesn't seem to be jittering when comparing to the background. The jittering only occurs when walking, not when looking around so that the object follows. I'm kinda out of ideas as for what could be the problem, so all help is appreciated!

Here's the logic for walking:

void Update()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    direction = Vector3.zero;
    direction = (transform.right * x + transform.forward * z).normalized * speed;

    if (controller.isGrounded)
    {
        yVelocity = 0;
        if (Input.GetButtonDown("Jump"))
        {
            yVelocity = jumpForce;
        }
    }

    yVelocity += gravity * Time.deltaTime;
    direction.y = yVelocity;

    controller.Move(direction * Time.deltaTime);
}

And the logic for making the cube follow the crosshair when picking it up:

public void Update(){
    if (isInteracitng)
    {
        pickupPoint = Camera.main.transform.position + Camera.main.transform.forward * pickedUpDistance - pickupOffset;
        rb.velocity = Vector3.SmoothDamp(rb.velocity, (pickupPoint - transform.position) * smoothForce, ref refVelocity, smoothTime);
    }

}

Also a video demonstrating the problem:

candid elm
rigid island
#

^^ ideally you want to move rigidbodies in FixedUpdate

#

Input should however be captured in Update

inland pawn
rigid island
#

also is Interpolation on

candid elm
rigid island
#

more than likely is physics rigidbodies move at FixedUpdate and CharacterController is moved on Update

inland pawn
candid elm
#

uhhhhhh
how do i fix this

#

is this how you store a dotween action in a variable

rigid island
#

i believe Tween is the type yes

candid elm
#

what could be a reason for killing the tween

rigid island
#

I haven't explored dotween too much, i'm gonna assume its kind of like Coroutine?

#

maybe the object was disabled/destroyed or Timescale?

candid elm
candid elm
#

now it works FINALLY

#

after 3 days

#

thanks

rigid island
#

nicee catch!

merry stream
merry stream
#

well its a code question

#

mainly

leaden ice
#

but this is a rabbit hole I've been down many times, and trust me it's 10x simpler if you just make 10 separate actions

#

Skill1
Skill2 etc

merry stream
#

ah okay

#

so dont have everything on one map

#

then have 10 references in the code?

leaden ice
#

Look how world of warcraft does it

#

imagine writing code to make this UI

#

With 10 actions, much easier

merry stream
#

alright

leaden ice
#
InputActionReference[]``` works
merry stream
#

check the code to see

#

ah okay, then just index by which button

#

also, is action type "value" and control type "any" for something like this?

leaden ice
#

Why not Button

merry stream
#

no clue

leaden ice
#

Again I'm recommending making 10 separate actions, each one a regular Button action

merry stream
#

kk

merry stream
leaden ice
#

Not sure what you mean by that

merry stream
#

in the code

leaden ice
#

You'd have to be more specific. There are many ways to use the input system

merry stream
#

im going to change the index stuff

#

is that the correct way to subscribe and do I need to enable/disable

#

someone was saying earlier that its wrong

#

even though it works

leaden ice
leaden ice
merry stream
#

is it necessary to unsubscribe?

leaden ice
#

That depends on whether the subscriber of the action has a shorter lifespan than the action asset itself

merry stream
#

okay, so just to keep it clean, i dont use a lambda and instead subscribe/unsubscribe with a for loop

leaden ice
#

I don't thnik those are mutually exclusive

merry stream
#

"If you want to unsubscribe you just can't use a lambda" am I misinterpreting?

#

since I am doing it in array, i dont need the ctx

leaden ice
#

well you either need an actual function (per action) or you need to store the lambdas in an array for later unsubscribing

leaden ice
merry stream
#

which is just the index

leaden ice
#

Sure but you can't pass that index into the function without a lambda or something else

gray mural
merry stream
#

ah yeah

gray mural
#

You will have to subscribe it to an actual method without adding the additional parameters

onSomethingHappenning += YourMethod;

onSomethingHappenning -= YourMethod;
merry stream
#

yeah, do you recommend making methods for each skill or leaving it how it is? also, do I need to enable/disable the action as well ie abilityActions[i].action.Enable();

leaden ice
#

You can do something like:

Action<CallbackContext>[] lambdas = new[10];

// subcribe:
for (int i = 0; i < abilityActions.Length; i++) {
  int actionNumber = i;
  lambdas[i] = ctx => TryUseSkill(actionNumber);
  abilityActions[i].action.performed += lambdas[i];
}

// unsub:
for (int i = 0; i < abilityActions.Length; i++) {
  abilityActions[i].action.performed -= lambdas[i];
}```
leaden ice
#

btw yes the "actionNumber" thing is necessary due to lambda variable capture

gray mural
merry stream
#

    private void OnEnable()
    {
        for (int i = 0; i < abilityActions.Length; i++)
        {
            abilityActions[i].action.Enable();
            int actionNumber = i;
            lambdas[i] = ctx => TryUseSkill(actionNumber);
            abilityActions[i].action.performed += lambdas[i];
        }
    }

    private void OnDisable()
    {
        for (int i = 0; i < abilityActions.Length; i++)
        {
            abilityActions[i].action.Disable();
            abilityActions[i].action.performed -= lambdas[i];
        }
    }
#

look good?

gray mural
leaden ice
#

actionNumber is necessary

#

otherwise you'll get lambda variable capture on the i variable

#

and all of your actions will act as if they use the skill at abilityActions.Length

gray mural
#

Oh, right

chrome berry
#

And that's a fun bug to figure out down the road when it breaks 😄

naive swallow
#

My nemesis, Lambda Capture

chilly surge
#

Oh what a coincidence that I was just talking in #archived-code-advanced earlier about reactivity systems having the ability to automatically unsubscribe, and the internal mechanism essentially boils down to the exact same code.

gray mural
merry stream
#

is there a way within the input asset to make it repeat while held or do I just handle that in code?

leaden ice
#

handle it in code

merry stream
#

what method would I subscribe to?

#

isPressed?

gray mural
#

Are you using the new input system?

merry stream
#

yes

chrome berry
#

Are you using C# events?

merry stream
gray mural
gray mural
chrome berry
leaden ice
leaden ice
gray mural
merry stream
#

wont that double press when I press once though?

chrome berry
latent latch
#

'new' input system doesn't have continuous callback so that would require to poll that input unfortunately

unique ivy
leaden ice
#

Yes this is the way^^ those are like GetButton GetButtonDown, GetButtonUp

gray mural
leaden ice
#

it only happens when the control actuation changes

latent latch
leaden ice
#

if we're talking about a button, it's only when the button is pressed

#

if it's a joystick it's when the joystick changes actuation. It's not every frame.

gray mural
latent latch
#

I know you can boolean continous callback though for when you pressed or release

chrome berry
#

on performed only gives continuous input if it's on a vector2 like a joystick and you don't keep it perfectly still

unique ivy
#

You can check the context value of button type and while it’s = to 1 do action

leaden ice
#

yep if you're just holding the joystick to the right, you won't get a performed each frame

#

full stop if you need to do something every frame you should be using Update

merry stream
#

so i could just get rid of the subscribing and what not and just loop checking for IsPressed

#
    private void Update()
    { 
        for (int i = 0; i < abilityActions.Length; i++)
        {
            if (abilityActions[i].action.IsPressed())
            {
                TryUseSkill(i);
            }
        }
    }
leaden ice
#

yes

#

you could do that

gray mural
chrome berry
#

I should update my central input handling class for held down buttons. I think I'll have other classes subscribe with an action to call whenever the designated button is kept held down for a minimum of X seconds, and then retriggered every Y seconds after

leaden ice
#

unless you want TryUseSkill to happen every frame

merry stream
merry stream
chrome berry
merry stream
#

similar to holding a key while typing

chrome berry
#

One other benefit is that if you're doing lots of clean up or processing of the raw input before using it, then a central class can unify that all in one place
Or for things like a fighting game where inputs get parsed for special moves and you'd likely want that figured out in one spot, rather than your fireball code doing the work and then your piledriver code doing the exact same work, etc.

merry stream
#

okay, its not going to be too complex so I don't think it's needed

chrome berry
#

It's not something that's too difficult to refactor into a single class, if you do find you need it, so no need to worry and do it prematurely

light pond
#

how can i approach this with scriptable objects

leaden ice
#

unclear what you mean beyond this

light pond
#

like number A

chrome berry
#

So in game you drag one of those number blocks into the formula and it calculates it?

light pond
#

u dont drag in anything

chrome berry
#

Got it, you select the A you want, the B you want, and C changes

#

So the blocks wouldn't be numbers, but some kind of ingredient, item, resource, etc.
So you'd probably make a scriptable object that stores the data of those things
Another class for the clickable option that references which scriptable object is the data for it
And finally some overall class that tracks what options have been picked and determines the result once A and B are selected

#

Oh and probably a recipe class as a scriptable object which has references to A and B, and the C you get as a result
So that last class above goes through the list of recipes it has and finds the matching one to find C

lone musk
#

Hi i am helping make a tool that allow people to cad robots spesificly for the vex robotics compation and we want to add a feature which would allow people to import diffrent 3d models for stuff like custom plastic parts and stuff like that, how would i go about doing that?

heady iris
#

importing models at runtime, not in-editor, right?

lone musk
#

ya

heady iris
#

Not sure about FBX.

lone musk
#

anything for obj?

wraith cobalt
#

There are so many obj libraries that you'd need to see which fits your needs

rigid island
wheat spade
#

I'm trying to make a folder that is ignored on specific build platforms. In a IPreprocessBuildWithReport interface, I'm trying to move Assets/Server to Assets/Editor/TempBuild, then in a IPostprocessBuildWithReport move it back. AssetDatabase.MoveAsset either gives me the error Destination path name does already exist or Destination parent directory does not exist, in addition to an error that says access is denied. I've tried several workarounds with AssetDatabase, but nothing has worked. Does anyone have experience with this?

gray mural
#

No, there is no. And I don't really think you need it

#

Imagine setting both row and column count to 3 and having more than 9 elements in your group

#

If you still need it, you may write a script based on the Grid Layout Group to check when the child was added to the GameObject and remove it if needed

#

Right, let's say you want to have 4 columns and 6 rows.
Set the Fixed Column Count to 4 and manage the other logic via code.

#

Remove the oldest message just if the current messages count equals to 4 * 6 = 24

leaden ice
swift falcon
#

Hey all!

#

I'm trying to make a combat system, where the human will attack a pig and it will be knocked back, similar to Super Smash Bros

#

However, as you can see above, the knocback is not very good

#

I'm trying to understand the problem however it feels like I just am not handling it properly. I can't type out all the code at the moment until someone asks for a specific area of it, because it's handled by many functions.

#

this is my damage hitbox script however:

    public GameObject parent;
    public float allowedImmunityTime = 0.4f;
    public AttackHitbox attackHitbox;
    private float immunityTime = 0f;

    [Header("Feedbacks")]
    public MMF_Player DamageFeedback;

    public void Damage(GameObject attacker, Vector2 knockback, float damageAmount){
        if(immunityTime <= 0){
            DamagePopupGenerator.current.CreatePopup(transform.position + new Vector3(Random.Range(-0.5f, 0.5f), Random.Range(-0.5f, 0.5f), 0f), damageAmount.ToString(), Color.red);
            if(attacker.GetComponent<Rigidbody2D>().velocity.normalized.x != 0){
                parent.GetComponent<Rigidbody2D>().AddForce(new Vector2(attacker.GetComponent<Rigidbody2D>().velocity.normalized.x * knockback.x * 2f, attacker.GetComponent<Rigidbody2D>().velocity.normalized.y * knockback.y + knockback.y/4), ForceMode2D.Impulse);
            }
            else{
                parent.GetComponent<Rigidbody2D>().AddForce(new Vector2(Mathf.Sign(attacker.transform.localScale.x) * knockback.x, knockback.y), ForceMode2D.Impulse);
            }
            parent.GetComponent<Animator>().Play("Hit");
            immunityTime = allowedImmunityTime;
            DamageFeedback?.PlayFeedbacks();
            StartCoroutine("ImmunityFrames");
        }
    }

    private IEnumerator ImmunityFrames(){
        while(immunityTime > 0){
            immunityTime -= 0.01f;
            yield return new WaitForSeconds(0.01f);
        }
    }
#

The main part where we add force is parent.GetComponent<Rigidbody2D>().AddForce(new Vector2(attacker.GetComponent<Rigidbody2D>().velocity.normalized.x * knockback.x * 2f, attacker.GetComponent<Rigidbody2D>().velocity.normalized.y * knockback.y + knockback.y/4), ForceMode2D.Impulse);

#

Where knockback is a vector2 I define with two arbitary ints that match as a multiplier, and I'm adding the attacker's velocity onto the attack for direction.

thick terrace
#

maybe add some minimum value to the y speed too, your animation looks like a powerful upwards swing and that's not reflected in the code at all

swift falcon
open lake
#

Hey!
I'm trying to export a .gltf 3d model using Unity's GLTFast library and I came across this on the documentation. Any idea on what this means? I found the two assembly definition files but I dont know where to reference them

thick terrace
open lake
#

I haven't touched assembly definitions before this but Unity says that The type or namespace name 'Export' does not exist in the namespace 'GLTFast' (are you missing an assembly reference?)

thick terrace
#

if you can't turn that on, then you would need to make your own assembly definition and add it as a reference yeah

open lake
#

Thanks! I just found a github repo of the package and imported that and removed the package manager version. THen I was able to tick the auto reference

open lake
#

Oh, by the way, is there a way for a Unity build to export a gameobject as a prefab so that another build could read it sometime later?

#

asset bundles, maybe?

thick terrace
#

yeah, asset bundles or addressables, which is asset bundles in a trenchcoat

open lake
#

my addressables journey has been confusing so far

#

especially with my lack of cloud understanding

thick terrace
#

you can use it without any of the cloud stuff if you don't need it

open lake
#

if I have a script thats a component on a prefab but the script has been compiled on both builds, then would the references and other stuff transfer over via the prefab without any editor intervention?

thick terrace
#

oh at runtime? not really, prefabs don't exist at runtime

#

that would be more like a save system

open lake
#

I see

#

So this is the flow of my application

#

I import a 3d model, attach a script to it and tweak it a bit and reorder and reposition a few of the children in the 3D model. I have completed my project this far. Now I want to be able to package this gameobject (info about the transform of the GO, its children, the script that I attached to it and its values and references) along with the actual 3D meshes, the .glb . And I want to be able to load this package and get the exact same gameobject

#

both are builds of the same project

thick terrace
#

what part of this is happening at runtime?

open lake
#

All of it

#

I know bruteforcing it is an option

#

or atleast I hope so

#

put everything in a messy json and reconstruct it

thick terrace
#

you could look at formats other than json, but yeah you'll mostl likely need to serialize the data yourself, asset bundles won't work for this

open lake
#

I see okay

#

I came across this thing called the binary formatter

#

Well

cold parrot
thick terrace
#

yeah, it might work but there's various reasons it's not a good idea

cold parrot
#

The reason why it works is the reason why you can’t (shouldn’t) use it

#

technically you can duplicate a prefab’s yaml and store that to exchange your structures together with the assets but you’d have to basically rebuild the Unity editor’s serializer and asset database for runtime usage.

open lake
#

Hmm I feel like this is almost impossible considering theres models of size of about 60mb involved

cold parrot
#

It’s 100% not what unity is designed for though

open lake
#

agreed

thick terrace
#

BinaryWriter/BinaryReader are decent but you'd need to write a lot of the boilerplate serialization stuff yourself, i'd check out maybe protobuf of flatbuffers or one of those libraries

cold parrot
#

You will be fighting the engine at every turn

thick terrace
#

i use MessagePack but it's kind of fiddly to set up

fast timber
#

I have a lot of errors of this form:

The .meta file *** does not have a valid GUID and its corresponding Asset file will be ignored. If this file is not malformed, please add a GUID, or delete the .meta file and it will be recreated correctly

Can I somehow automatically tell unity to remove all meta files with invalid guids, but keep the rest?

cold parrot
#

all ‘safe’ serialization is terribly annoying to use 😄

open lake
#

sorry if this sounds annoying but 😅
where would one go about beginning the serialization process

cold parrot
#

What’s typically done is embedding an interpreted language for runtime execution

#

and using that to do all of your asset/prefab export/import

thick terrace
#

i'm not sure how adding an interpreter helps with that 😅

cold parrot
#

that works with regular unity asset bundles since Unity treats it all as data, and this would allow you to include code in your assets

cold parrot
thick terrace
#

oh for scripts, yeah, if you need to add new scripts in a bundle

#

idk if chipe needed that

#

if you just need to save which existing scripts from the base game are on a prefab, that can all be done with any serialization library

open lake
#

yup

cold parrot
#

an interpreted language, maybe a DSL, would just be a replacement for a complicated API that these assets would need to use declaratively

#

It’s all a big yuck to develop though 🙃

thick terrace
cold parrot
#

If you were using an engine where the# editor and runtime are the same app, it’d be a breeze to implement

open lake
#

is that why debug gizmos dont work in builds?

cold parrot
#

yes

#

But there are assets for that. You can still draw your own, but not through the builtin API

open lake
fast timber
#

I am getting errors of the form

The referenced script is missing on Shooter Spawner (index 2 in components list)

However, I do not have a gameobject called Shooter Spawner in my scene

#

does anyone know how I could find the GO the error is talking about?

gray mural
#

"index 2 in components list"

fast timber
#

or actually I don't know

gray mural
fast timber
#

if shooter spawner refers to the GO name or component name

gray mural
#

Well, this is definitely not a build-in component

fast timber
fast timber
gray mural
fast timber
#

but here is riders find-anything results - empty

#

let me maybe try find

gray mural
#

And how don't you know about your own scripts? Do you have so many of them?

fast timber
fast timber
fast timber
gray mural
#

You may also try finding it in Unity Assets

fast timber
#

I'll ask the support there, maybe they are still using some old files or something

gray mural
fast timber
# gray mural If it's a package you have installed, you can find the scripts in `Packages`.

I do not think its actually a GO. I now found more error messages of the form

The referenced script on this Behaviour (Game Object 'Shooter Spawner') is missing!
UnityEngine.Object:Instantiate<UnityEngine.GameObject> (UnityEngine.GameObject)
Rukhanka.Hybrid.AnimatorControllerBaker:ConvertAllControllerAnimations (UnityEngine.AnimationClip[],UnityEngine.Animator) (at ./Packages/com.rk.rukhanka/Rukhanka.Hybrid/AnimatorControllerBaker.cs:550)
#

I think it just has some old GO referenced somewhere and I do not fully know where, I'll find it though

#

Thank you for the help!

gray mural
grizzled dune
#

Good afternoon everyone
I have a question regarding in app purchases
So I'm pretty sure most of you know about Lucky Patcher, if not it's an app that bypasses your IAP and basically gives you free money
Is there a way to prevent Lucky patcher to not give free stuff and bypass your IAP? An example is Future Fight, the game is built on Unity however they don't let Lucky patcher bypass their IAP

leaden ice
grizzled dune
leaden ice
#

Do note however with something like this it's a never ending and ultimately losing battle

#

Since the user physically owns their own device there's ultimately little you can do to prevent them from controlling the software running on the device, if they are sufficiently motivated

#

If it's a network enabled game you can get away with judicious validation and ownership of the data stores keeping track of user items and currency etc

grizzled dune
grizzled dune
thick terrace
chilly surge
#

Someone can always make a cracked version of your app with everything purchased.

#

I have no evidence to back this claim up, but if you are making a single player game, people who are desperate enough to do these kinds of hacks, aren't likely the ones to ever purchase anything anyways.

sturdy kindle
#

Question about managing sound effects:

I began managing my sound effect files by creating an Audio Manager script that's applied to a game object which stores a list of my audio sources. I then reference to a specific file within other objects as needed.

I've read this may become an issue with memory as I'm loading all the files into the game, including the ones that may not be used in a specific scene.

Would it be better to apply the audio files to the objects that use them?

fleet furnace
opaque forge
#

Hello I'm trying to instantiate objects along specific positions and with correct rotation in script, but the pivot position of that object is on the corner instead of the center so when instantiated with a specific rotation like 90 degrees for instance, it rotates around the pivot point, therefore shifting the actual position. I tried to instantiate it in a parent to solve the problem but it still rotates around the pivot point. Can anyone point me in the direction to solve this issue

  parent.transform.position = position;
  Bounds bound = GetPrefabBounds(building[0]);
  Vector3 pivotOffset = position + new Vector3(bound.size.x / 2.0f, 0, bound.size.z / 2.0f);

  Instantiate(building[0], pivotOffset, Quaternion.Euler(0, Yrotation, 0), parent.transform);
  parent.transform.DetachChildren();
  Destroy(parent);
open lake
#

Hey I'm back

leaden ice
opaque forge
#

I have a huge amount of them and tought it would take a lot of time

open lake
#

I managed to build somewhat of a serializer for a gameobject and I've covered Mesh filter and transform components @cold parrot @thick terrace
But now the problem is parsing through all the children in the GO and then instantiating then all at once is taking a toll on my performance. How do I fix this?

#

Also stuck on materials

#

This is what I've come up with but the material part is still very errory

latent latch
#

load screen and cache em

fleet furnace
thick terrace
sturdy kindle
open lake
heady iris
#

Unity does not care about asset names.

fast timber
heady iris
#

I grep for GUIDs fairly often. It's more reliable than Unity's own "find references"...

#

usually when i'm seeing if i can delete an asset

fast timber
#

I found them using find/grep by searching all files for Shooter Spawner instead of ShooterSpawner

#

they were in a .prefab file

heady iris
#

Ah, I see!

fast timber
#

then I checked that prefab and saw that it has deactivated child gameobjects which reference those scripts

versed spade
#

I have many areas in my code that require themselves to be updated a little bit to accomadate whenever I had a new weapon type. Are there are programmer techniques or VSC extension that will make it easier to track these. They will be in multiple different files

chilly surge
#

What kind of changes?

#

Ideally, you would write code in a way that the compiler does it for you, by causing compile errors unless you have properly implemented things.

placid summit
#

Has anyone done an inverted mask for UGUI? struggling with examples

heady iris
#

the whole open-closed principle

#

Is there a better way to detect that the game has changed screens than constantly comparing the current list of resolutions to an old list of resolutions?

#

I need to update my settings menu when this happens

heady iris
#

I'm pretty sure Displays.onDisplaysUpdated does not fire when this happens

#

(it's not even in the documentation!)

versed spade
# chilly surge What kind of changes?

Basically I have 3 weapon types: Repeater, Ballistics, Cannon. If I add another called... Beam it will not choose the right set of stats until I manually update weapon logic to include it

chilly surge
#

How are your code currently structured? That sounds like a design issue.

#

One way to do it is to have the stats on the weapons themselves, eg a Weapon base class or an IWeapon interface that has Stats property.
Whatever that needs the stats would just do currentWeapon.Stats to get it, it would not involve updating any code.

versed spade
#

Probably I'll thread the code here:

#

Or not clyde says no

#
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

[CreateAssetMenu(fileName = "New Weapon", menuName = "Weapon")]
public class WeaponObject : ScriptableObject
{
    #region Variable Declaration

    [Header("Visuals and Information")]

    [Tooltip("Make sure the model is a PNG and has been set to Point Rendering")]
    public Sprite model;
    public new string name;
    public string description;

    public enum weaponType { Nothing, Repeater, Ballistic, Cannon }

    [Tooltip("Here you can specify the weapon type which will change the stats it uses.")]
    [SerializeReference]
    public weaponType type;


    [Header("Weapon Stats")]
    
    public RepeaterStats repeaterStats;
    public BallisticStats ballisticStats;
    public CannonStats cannonStats;
   
    #endregion
}

#region Weapon Variables

[System.Serializable]
public class RepeaterStats
{
    public int maxChargedAmmo;
    public float laserDamage;
    public float lasersPerMinute;
    public float dropoffDistance;
    public float chargingSpeed;
    public GameObject projectile;
}

[System.Serializable]
public class BallisticStats
{
    public int maxBallisticAmmo;
    public float bulletSpread;
    public float bulletDamage;
    public float bulletsPerMinute;
    public float heatLimit;
    public GameObject projectile;
}

[System.Serializable]
public class CannonStats
{
    public int maxCannonShells;
    public float shellDamage;
    public float reloadTime;
    public GameObject projectile;
}

#endregion

This is the code for the weaponObject itself. Each class is belonging to a different weaponType

#
    void Start()
    {
        playerControls = new PlayerInputs();
        playerControls.Enable();
        weaponType = weaponData.type.ToString();

        // Make changes to this as new weapons are added
        switch (weaponType)
        {
            case "Repeater":
                fireRate = 60 / weaponData.repeaterStats.lasersPerMinute;
                break;
            case "Cannon":
                fireRate = weaponData.cannonStats.reloadTime;
                break;
            case "Ballistic":
                fireRate = 60 / weaponData.ballisticStats.bulletsPerMinute;
                break;
        }
    }```
#

sorry other poster 🙏

grand compass
sleek bough
#

@versed spade Use paste sites to post large blocks of code !code

tawny elkBOT
heady iris
versed spade
heady iris
#

that's when you send a file

#

but then mobile users cannot read your code

versed spade
#

ah 😦

heady iris
#

use a paste site

versed spade
#

will try

fervent furnace
#

to the one who delete their question
i think it is nearly impossible to get a non axis-aligned bounding box (call it NAABB below
consider a triangle, there is only one AABB of it, but for NAABB you can have 3 (if you make the NAABB aligns one of its side)

grand compass
heady iris
#

you can compute a bounding box in an object's local space

fervent furnace
#

ofc you can somehow define its "major axis" then for all other vertices, get their distances to the axis and bound it

#

ah, compute (get) the AABB in local space then rotate it

grand compass
#

I'll try to think about your possible solutions. Thank you so much, both of you!

heady iris
#

and I can then check if the height/width/refresh rate/name changed

#

this allegedly produces no garbage

#

grumble. 42B allocation.

knotty sun
heady iris
#

ah, it's an Editor-only allocation

edgy stump
#

Yoooo what's happened?

#

Can't open project after making copy of project for github repo path

#

also can't exit from safe mode ☠️

vapid lynx
#

I have a missle and a mesh with other objects like trees and stuff. I want the rocket to rotate to avoid the obstacles and mesh. However this code just doesnt work and im confused why

heady iris
#

is _rotateSpeed non-zero?

#

if it is serialized, look in the inspector

edgy stump
vapid lynx
heady iris
#

ah, your rotation is backwards

#

do transform.rotation * ...

#

Q1 * Q2 is the result of applying Q1 followed by Q2

vapid lynx
#

huh?

#

Quaternion avoidanceRotation = Quaternion.FromToRotation(transform.forward, -surfaceNormal) * transform.rotation;

#

oh this line?

heady iris
#

Quaternion multiplication is not commutative: A * B != B * A