#archived-code-general

1 messages · Page 342 of 1

heady iris
#

also consider logging in the bullet's Start method, with a message that includes GetInstanceID()

next sparrow
#

Hello everyone, I'm trying to find some ways to reduce my code since the logic is quite similar but I can't find a way.

#
                case "gender":
                    valuesLabels = new string[EventsXmlEnum.GenderLabel.Count];
                    valuesCodes = new string[EventsXmlEnum.GenderLabel.Count];
                    i = 0;
                    foreach (KeyValuePair<EventsXmlEnum.Gender, string> pair in EventsXmlEnum.GenderLabel)
                    {
                        valuesLabels[i] = pair.Value;
                        valuesCodes[i] = pair.Key.ToString().ToLower();
                        i++;
                    }
                    break;
                case "activity":
                    valuesLabels = new string[EventsXmlEnum.ActivityLabel.Count];
                    valuesCodes = new string[EventsXmlEnum.ActivityLabel.Count];
                    i = 0;
                    foreach (KeyValuePair<EventsXmlEnum.Activity, string> pair in EventsXmlEnum.ActivityLabel)
                    {
                        valuesLabels[i] = pair.Value;
                        valuesCodes[i] = pair.Key.ToString().ToLower();
                        i++;
                    }
                    break;```
heady iris
#

Clicking on the log message will highlight whatever object produced it, assuming you added this as the context

gray mural
#

Log it every frame and check when it gets not assigned

next sparrow
#

I have a switch with several cases which focus on dictionaries with different enum keys. Is there any way to make a single loop and pass the enum type as a variable ?

gray mural
next sparrow
heady iris
#

ah

#

that explains things

#

you are referencing a prefab somewhere

next sparrow
heady iris
#

although, Instantiate is static, so it shouldn't really matter if the prefab gun is instantiating a prefab bullet

#

it's not like the bullet would go somewhere different than if an actual gun instance instantiated the prefab bullet

gray mural
next sparrow
#

Yes, it's a dictionary, but its key is an enum

#

Two different dictionaries with two different enums as key. The value of the dictionaries are both string though

#

No

knotty sun
next sparrow
heady iris
#

The enum values are integers.

#

The values simply have names.

next sparrow
#

Hm, does it mean I could use a for loop instead ?

heady iris
#

You can't cast from KeyValuePair<SomeEnumType, string> into KeyValuePair<Enum, string>, but you can iterate over the dictionary's keys like so:

foreach (Enum key in dict.Keys) {

}
next sparrow
#

Yes, but how does that help with creating a method to makes both dictionary work at the same time ?

#

Because even if I create a method, I'd need to pass the dict as a variable ? Which mean I'd need to cast it to its related enum

#

Though I'm thinking I'm actually using the enums as strings in the end. I could reduce the size of my code by transforming my enum to a list<string> and pass that to the method instead since I don't actually care about the enum type in the end.

heady iris
#

It's a bit difficult to wrangle the generic types here.

gray mural
heady iris
#

You could write an IEnumerable<Tuple<string, string>> method that takes a Dictionary<K, string> and that yields the key names and values as tuples

gray mural
#

So both are Dictionaries with different keys, if I get it correctly

next sparrow
heady iris
#
IEnumerable<ValueTuple<string, string>> GetPairs<K>(Dictionary<K, string> dict) {
  foreach (var pair in dict) {
    yield return ValueTuple.Create(pair.Key.ToString(), pair.Value);
  }
}
#

i think those are the right method names, at least

gray mural
heady iris
#

(i used ValueTuple because it nominally reduces the amount of garbage you create; that's not terribly important)

#

You could also directly write into the arrays if they're fields of your class, yeah

next sparrow
# gray mural Yeah, so it does work

How does creating 2 methods makes the code simpler ? It would contain the exact same code as in the switch, wouldn't it ? I wanted to find a way to have a single method handle both enum, because I'll have 10 more enums this way

gray mural
next sparrow
#

I can't use Dictionary<Type, string>

gray mural
#

This should work for both cases

heady iris
next sparrow
#

Type is not valid

next sparrow
heady iris
#

it's a value type that's basically just

#
public struct ValueTuple<T1, T2> {
  public T1 Item1;
  public T2 Item2;
}
#

defined for varying numbers of items

next sparrow
#

Hm interesting. That seems to solve my problem indeed. I'll give it a shot. Thanks!

#

But the return in VS says (string, string). How do I use the method ?

heady iris
#

it's a pair of strings

next sparrow
#

I've never since this type of return

heady iris
#

because it's a tuple

#

var (foo, bar) = ("one", "two");

#

i hope that's actually the right syntax

#

oops, single quotes

#

i've been writing python recently

heady iris
gray mural
# next sparrow Type is not valid
private void Example<T>(Dictionary<T, string> values)
{
    valuesLabels = valuesCodes = new string[values.Count];

    for (int i = 0; i < values.Count; i++)
    {
        var value = values.ElementAt(i);

        valuesLabels[i] = value.Value;
        valuesCodes[i] = value.Key.ToString().ToLower();
    }
}
heady iris
#
foreach (var (key, val) in GetPairs(dict)) {
  // ...
}
#

there we go

#

perhaps the gun config has a bullet life of 0

next sparrow
heady iris
next sparrow
#

Thanks a lot @heady iris !

heady iris
#

okay, so do some logging to find out if the bullets are getting instantiated at all (check if Start runs)

#

find out when they destroy themselves

next sparrow
heady iris
#

What does this mean? Do you see them in the hierarchy?

#

That just proves that the message was logged

#

Where’s the proof that you actually created a new instance?

#

e.g. logging the new instance

leaden ice
#

You should log something in all those if statments. What if those statements are not passing

#

(i.e. it doesn't have those components)

heady iris
#

You've got a lot of GetComponents in here

#

Get rid of them. Put public fields on your bullet class that reference those components

#

then reference the bullet prefab as a Bullet instead of as a GameObject

leaden ice
#

I'd probably just make the Bullet script handle all this, and pass it the gunConfig reference to do all its business

heady iris
#

yes

leaden ice
#

exactly

#

        Bullet bulletScript = bullet.GetComponent<Bullet>();
        if (bulletScript != null)
        {
            bulletScript.SetDamage(gunConfig.bulletDamage);
            bulletScript.SetLife(gunConfig.bulletLife);
            bulletScript.SetExplosive(gunConfig.explosiveAmmo);
            bulletScript.SetPenetration(gunConfig.bulletPenetration);
            bulletScript.SetImpactParticle(gunConfig.bulletImpactParticlePrefab);
        }```
This is crazy
#

why not just:

bulletScript.Setup(gunConfig);```
#

the rest happens inside Bullet

heady iris
#

instead of a wall of GetComponent and setter-method calls

heady iris
#

Now make it set its velocity in Start, as well as turn its sprite renderer on

#

The gun should not have to dig around in the game object to find random components.

#

It should just tell the bullet that it's been fired

heady iris
#

Your prefab has a Bullet on it. Bullet has public fields on it that hold references to the components you need.

#

Later, you can make the fields private and move the behavior into a method (just like you've done here with Setup)

#

But for now it can literally just be a public SpriteRenderer bulletRenderer; field on Bullet

#

Zero GetComponent calls are needed.

#

Assign the reference in the bullet prefab.

#
public class Bullet {
  public Rigidbody rb;
}

...

public class Gun {
  [SerializeField] Bullet bullet;

  public void Shoot() {
    var shot = Instantiate(bullet);
    shot.rb.velocity = Vector3.forward;
  }
}
#

That's it.

#

In the bullet prefab, drag its Rigidbody compoennt into the rb field

next sparrow
#

I have a problem similar to my question above which was about dynamic enums

rigid island
#

^^ this is a sure way you know everything is plugged in

next sparrow
#

This time it's dynamic classes

#
                case "map":
                    valuesLabels = new string[Maps.instance.list.Count];
                    valuesCodes = new string[Maps.instance.list.Count];
                    i = 0;
                    foreach (KeyValuePair<string, Map> pair in Maps.instance.list)
                    {
                        valuesLabels[i] = pair.Value.label;
                        valuesCodes[i] = pair.Key;
                        i++;
                    }
                    break;
                case "job":
                    valuesLabels = new string[Jobs.instance.list.Count];
                    valuesCodes = new string[Jobs.instance.list.Count];
                    i = 0;
                    foreach (KeyValuePair<string, Job> pair in Jobs.instance.list)
                    {
                        valuesLabels[i] = pair.Value.label;
                        valuesCodes[i] = pair.Key;
                        i++;
                    }
                    break;```
#

all my classes have a "Label" field. Is there anyway to centralize my code into one method like before ?

heady iris
#

You could create an interface.

#

ILabeled, perhaps

#

It would declare a property called Label

#

note that this is not a field

#
public interface ILabeled {
  public string Label { get; }
}
#

each class that implements the interface must have a Label property

#
using UnityEngine.Localization;

namespace Pursuit.Interfaces
{
    public interface IDescribable
    {
        public LocalizedString Label { get; }
        public LocalizedString Description { get; }
    }
}
#

i have something similar going on

next sparrow
#

Once they have the interface, how would that work in the method ?

#

Oh, what's the LocalizedString type ?

heady iris
#
public void DescribeIt(ILabeled labeled) {
  Debug.Log(labeled);
}
next sparrow
#

Ok thanks

heady iris
#

it can be turned into a string in various languages

next sparrow
#

Damn, I didn't know about that lol. I'm using a custom translation class and some external json files

#

I'll have to look into it. Thanks for the tip !

heady iris
#

The former is worse in every way.

#

It's brittle (you depend on exact GameObject names and on the exact hierarchy layout)

#

It's also slower (you have to search for the child by name)

#

Optimization is more-or-less irrelevant here, though

#

You should be much more concerned about correctness

#

sounds more like the bullet isn't visible

rigid island
#

You could put a Debug.Break() after you instantiate it then look for it on the hierarchy , select it and press F in the scene view.

#

it will pause the simulation

#

so you can see whats happening to bullet

#

yes, you would have to debug it

#

bingo

#

there are usually lots of system trying to work in harmony together , you gotta be like the maestro know whos doing what at all times

#

yeah

#

then you can even press the advance by frame button

#

its an engine! take advantage that its a simulation and not "real life"
sometimes for debugging I slow my timescale to nearly 0

next sparrow
#
    {
        valuesLabels = valuesCodes = new string[values.Count];

        for (int i = 0; i < values.Count; i++)
        {
            var value = values.ElementAt(i);

            valuesLabels[i] = value.Value.Label;
            valuesCodes[i] = value.Key;
        }
    }```
I'm trying this way but it says .Label does not exists on the IEntity when the interface does have the public string.
heady iris
#

This has nothing to do with the IEntity interface

#

Get rid of the generics.

next sparrow
#

Oh yeah, the copy/paste from the enum version had the type which is not needed here

#

Thanks!

heady iris
#

Pause the game. Select the bullet in the hierarchy. Look at it.

#

You don't need to squint at pixels or log huge amounts of stuff here

#

Select the bullet and look at where it is and which components it has.

#

If there is no bullet in the hierarchy, then it's immediately destroying itself after its creation.

vale bridge
#

Is using the subscriber pattern for player controls a good idea, or is there some sort of built in thing that would be better than whatever junk I write

next sparrow
#

Hm, still not working.

heady iris
next sparrow
#

InitValuesFromEntity(Scenarios.instance.list, ref valuesLabels, ref valuesCodes);
The list is a dictionary of <string, Scenario> and the Scenario class implements the IEntity

heady iris
#

either by subscribing to an event or by having it send messages

heady iris
#

Dictionary<Foo, Bar> is not compatible with Dictionary<Foo, IEntity>.

#

Right, duh.

#

So you will be using generics!

next sparrow
#

Oh lol

vale bridge
heady iris
#
public void DoSomething<T>(T arg) where T : IEntity { }
vale bridge
next sparrow
#

Too bad, that would have solved that

heady iris
#

You can constrain the generic type parameter.

#

It can now be anything that derives from IEntity

heady iris
#

No.

#

But it does explain why the bullet is invisible

vale bridge
heady iris
#

Sprite renderers don't have anything to do with collision

heady iris
next sparrow
#

But is it possible to pass a dictionary of class derived of IEntity ? Because I'd need to pass various dictionaries directly

vale bridge
heady iris
#

you'll do this with a Dictionary<string, T>

next sparrow
#

Ohhh ok. Sorry, first time trying to code this way

#

I see. I'll try

#

I'm afraid I'm still stuck :X

InitValuesFromEntity(Scenarios.instance.list, ref valuesLabels, ref valuesCodes);
void InitValuesFromEntity<T>(T values, ref string[] valuesLabels, ref string[] valuesCodes) where T : Dictionary<string, IEntity>

The error says it cannot convert Scenario to IEntity ? But Scenario does implement IEntity

#

Did I mess it up somewhere in the code ?

#

Ok nevermind, I did mess up, the T is supposed to replace the IEntity only, not the whole dictionary
void InitValuesFromEntity<T>(Dictionary<string, T> values, ref string[] valuesLabels, ref string[] valuesCodes) where T : IEntity
This works now. Thanks a lot @Fen. You're on fire tonight 😉

heady iris
#

you don't need to pass the arguments as ref

#

unless you are assigning to the arrays, I guess

#

in that case go nuts

#

you need to pay way more attention to what you're doing, then

#

you've got references pointing all over the place

swift falcon
#

hi so I've tried to create a duplicate inventory system to one i already have and I'm trying to figure out what the issue is here, it's meant to pick up the picture and add it to the wallet inventory but it doesn't pick it up or add it properly. Is it something with me changing names? I only changed names so that it wouldn't interfere with the other inventory system, I can show the scripts for it if needed.

leaden ice
#

You seem to have a NullReferenceException here

#

I would start with that

swift falcon
swift falcon
leaden ice
#

identify what is null and why

#

and fix it.

#

go to the filename and line number indicated

leaden ice
#

What are "basic items" and "wallet things"

swift falcon
#

like i just wanted items to go into different inventory systems for asthetic reasons

leaden ice
#

It's not clear what you mean by "inventory system"

heady iris
#

you don't need to copy-paste your code if it's just putting the items in two different places

#

This kind of code is probably why it's not working

leaden ice
#

To me "inventory system" means a bunch of code that makes inventories work

#

You certainly don't need more than one set of such code

heady iris
#

digging around the hierarchy by name and using GetComponent all over the place

#

You should have a StoredItem component that has fields for things like the text and image components

#

reference the prefab as a StoredItem, not a GameObject

swift falcon
#

I did this for the other one and it works so I'm confused

#

how would I have one script put items into two different locations?

rigid island
#

you never should have to GameObject instance = Instantiate etc.. thats pretty useless tbh

swift falcon
#

I was following a tutorial thing ngl

rigid island
#

tutorial is bad

leaden ice
rigid island
#

ItemUIThing uiInstance = Instantiate etc..
uiInstance.Setup(stuff etc

leaden ice
#

tutorials are for getting ideas and understanding techniques. They're not for creating a finished system that you apply directly to your game

#

you use the techniques to build your own system that works in your game

gusty aurora
#

If there an way to spawn a VFX graph at a list of positions (with only one component) ?

#

I remember reading about sampling positions from a texture

swift falcon
leaden ice
#

once you learned, you build your own similar system but in your game

#

the reason it's not working is obvious - you're getting a NullReferenceException

#

Your code is looking for very specifically named objects in very specific places

#

which don't exist here presumably

#

If you don't understand any of this it doesn't seem like you understand your code at all

#

Which means it's probably time to stop trying to implement inventory systems and time to go learn scripting / C# basics.

swift falcon
leaden ice
#

I know you're new

#

and that's why I'm recommending you start with the basics

#

You may think you understand the basics but if you don't understand a NullReferenceException or how to fix it, then you do not understand the basics

swift falcon
#

that is why I'm asking but okay

leaden ice
#

And I have given you advice already on where to start

#

go to the filename and line number indicated in your error and figure out which reference is null and why

royal gulch
#

Is there a way to make a UI Image block mouse input so that the OnMouseEnter function is not called on game objects covered by the UI Image?

leaden ice
#

Use IPointerEnterHandler

#

and you will get this behavior for free

swift falcon
royal gulch
leaden ice
#

and make sure oyu're looking in the correct file

leaden ice
royal gulch
leaden ice
#

It always does!

gray mural
#

When my ScriptableObject is renamed, I rename an Asset associated with it, whose variables seem to be reset. The methods I have tried to save the changes with are listed in the order I've tried calling them:

EditorUtility.SetDirty
AssetDatabase.SaveAssets
AssetDatabase.Refresh
#

However, this does not seem to work. Nothing happens with the Asset when not renaming it via AssetDatabase.RenameAsset

deep oyster
#

What's the best way to do a double ended queue?
I have a history of locations, I only want to store the most recent ones (Adding as location gets updated, removing from the back as you get too far away), but I don't know exactly how many recent ones I want to store at any given time

knotty sun
deep oyster
#

oh my god you're right I'm so dumb

onyx osprey
#

I have this scene which works fine in the editor but when building I get this parsing error , I went to look at the file in code and it looks just fine at those lines

rocky tide
#

This is the screen. I want to make a grapplinghook for the player to shoot a raycast on the wall. The problem is that I am trying to make this on mobile so the player has to click on the screen to show where the grapple would go to. And Im not sure how it would go because the grapple is in the player. This is in Unity3D and I have been battling this for couple of days how to implement it. Any tips?

#

This is the code where I start the grapple. I havent gotten into grapple execution part because the start of the grapple is already so challenging for me.

rigid island
#

get the result of the Hit that point by doing a ScreenToRay

rocky tide
#

@rigid island I feel dumb

rigid island
rocky tide
#

I was trying to find the thing for that 5 minutes later. Heyy use ScreenToRay.

#

😄

rigid island
#

Ohh Okay lol

#

you still need way to store that pos, just for showing purposes like if you're trying to make a marker

rocky tide
#

But the original Position of the Raycast comes from the gun that the player is holding. So is it: Take the Raycast end point from the ScreenToRay, save it and create a new vector that is the Guns position and the end point?

#

Ok I think I got something from this conversation. Thank you @rigid island

wild vigil
#

How can I configure this in my Unity project. I don't want to set "Dev Build"

#

^this is using Android Studio

chilly surge
swift falcon
#

what's considered good practice when it comes to data that needs to be saved?
for example a Player Monobehaviour has a Inventory variable that needs to be saved, should Player have a function to serialize and deserialize the Inventory or should Inventory be serialized and initialised with a function that takes in the saved Inventory? or another way?

glass rover
#

turns out when you hide your events manager that handles panel changing while changing panels you can't change panels anymore Mike

cosmic rain
# swift falcon what's considered good practice when it comes to data that needs to be saved? fo...

There aren't really "good practices" in regards to specific features.
The way I'd implement it is by having a set inventory method on the character that assign the inventory data to it's inventory. This function would be called from some kind of manager, like GameManager or PlayerManager, that would take care of loading the inventory with the rest of the player data.
Similarly, the save process would be handled by the game manager, perhaps involving some events.
I can already see some issues with it, though, so it's probably gonna take several iterations of trial and error to make a good system.

swift falcon
#

okay gotcha ty, that's basically what i do now with Monos having a specific Data object tied to them that's assigned with a function
one issue i've found is if the gameobject is deleted the data still exists in the code not tied to any object, so it keeps running and has a high chance of causing an exception

spare island
#
    private AIBrain _brain;
    public AIBrain Brain { get => _brain; }
    private void Awake(){
        _brain = new AIBrain(this);
    }
    private void Update(){
        if (_brain == null){
            Debug.LogWarning("Brain is <color=red>null</color=red> at Update");
        }}

    private void FixedUpdate(){
        if (_brain == null){
            Debug.LogWarning("Brain is <color=red>null</color> at FixedUpdate");
        }}

Why would a variable be null on FixedUpdate but not on Update?

#

I am perplexed

#

Debugging it just gave me more questions

cosmic rain
spare island
cosmic rain
#

Another possibility is that you have several of these scripts both with assigned and not assigned value

spare island
#

but if its destroyed than how would it exist on update..

cosmic rain
#

But yeah, it might imply that there's a difference between fixed update and regular in how the null check works, so I don't think that's it

spare island
#

oh wait i think i got it, i think i'm overwriting it in an inherited class

spare island
#

technically that was the correct answer, but it was an inherited class not multiple of the same script

hasty wave
#

what's Unity 6??

rigid island
hasty wave
#

:|

rigid island
# hasty wave :|

ya it used to 5, then it went all wacky with years n stuff then they decided that aint cool nomo . So now its 6

hasty wave
#

no I mean- what's difference from other editor version?

simple ruin
#

How do you debug shaders not working? I've been having shader issues with the built version of my game using glTFast, where they work fine in the editor, but don't in the built version. I tried adding a shader variant collection and added it to preloaded shaders, and while that fixed most of the textures, some still show up wierdly, like the chair in the image still showing up as silver. I'm pretty confident its a shader issue since I've fixed most of the textures with the variant collection, but I'm not sure if I missed any

#

I tried enabling developer mode to access the debug console in the built version but glTFast doesn't give me any errors or anything like that regarding missing textures/shaders

cosmic rain
cosmic rain
simple ruin
lusty locust
#

Am I understanding this correctly? First time setting up a state machine and I think I mostly understand how the logic works. The way this constructor argument is setup vs something like MonoBehaviour is that I'm strictly defining the variables in each state I'm passing as a reference to the player's main script? This is the call that would explicitly make it happen (minus the rest of the setup)?

#

I realized it's a very vague question to say something like "am I understanding how constructors work instead of just copying what I see on a YT screen" lol.

cosmic rain
lusty locust
#

It's setting values for each "new state" (or in this case as I enter a state).

simple ruin
#

but nothing about using a different graphics thing than the editor

west lotus
cosmic rain
simple ruin
cosmic rain
# simple ruin

Do you see the auto graphics API for windows/Linux/mac? Uncheck that and a list would appear.

simple ruin
#

ah at the top. Got it

lusty locust
#

The more time passes the more I learn there are a lot of bad tutorials out there.

simple ruin
cosmic rain
#

Though, I'd imagine that editor uses d3d11 or 12 on windows.

west lotus
craggy pivot
#

This might be a done to death question, but my struct isn't appearing in the inspector. A google search didn't really help
Struct Definition:

[System.Serializable]
public struct DataTag : INetworkSerializable
{
    FixedString32Bytes key;
    float value;

Implementation:

public class ItemDescription : ScriptableObject
{
    public GameObject prefab;
    public Sprite icon;
    
    public ItemType itemType;
    public uint weight;
    public DataTag dataTag;
}```
rigid island
#

also not even sure FixedString32Bytes is serializable ?

craggy pivot
#

wow how did i miss that

#

Thank you

hasty wave
#

uhm.. how do I solve this error?

SceneView rotation is fixed to identity when in 2D mode. This will be an error in future versions of Unity. UnityEditor.GenericMenu:CatchMenu (object,string[],int)

leaden ice
#

Looks like a warning at worst

raven basalt
#

I am trying to make a conveyor belt that moves every rigid body on it a certain direction. Howerver, this doesn't seem to be working:

using UnityEngine;

public class ConveyorBelt : MonoBehaviour
{
    public float speed = 5f; // Speed at which the conveyor belt moves objects

    void OnTriggerStay(Collider other)
    {
        // Check if the object has a Rigidbody component
        Rigidbody rb = other.GetComponent<Rigidbody>();
        if (rb != null)
        {
            Debug.Log("ConveyorBelt: Rididbody detected");
            // Move the object along the conveyor belt
            rb.velocity = new Vector3(speed, rb.velocity.y, rb.velocity.z);
        }
    }

    void OnTriggerExit(Collider other)
    {
        // Reset the object's velocity when it leaves the conveyor belt
        Rigidbody rb = other.GetComponent<Rigidbody>();
        if (rb != null)
        {
            rb.velocity = Vector3.zero;
        }
    }
}
dusk apex
vivid halo
# raven basalt I am trying to make a conveyor belt that moves every rigid body on it a certain ...

What doesn't seem to be working?

Translated from code into English, this says:

When another object whose collider is set to IsTrigger continues to collide with me and has a rigidbody, set that rigidbody's velocity to (x = speed, y = its own pre-existing y-velocity, z = its own pre-existing z velocity). Whenever it stops colliding with me, set its velocity, if it has a rigidbody, to zero.

It could be failing for a few reasons:

  1. You did not intend to only set the other rigidbody's x-axis movement vector to a velocity of 5f
  2. OnTriggerStay and OnTriggerExit trigger rapidly while an object bounces around on top of the conveyer belt
  3. The colliding object collided with a child object, so GetComponent<Rigidbody>() is returning false and exiting early
  4. The speed is too little to be visually recognized
  5. The script is not attached to the correct object
#

Add more debug logs and find the exact point of failure if you can.

kind cloak
#

Hi ! How can i get this value as a variable from the mixer ? i know how to get the fader value but this one i can't find a way to do it

deft hornet
#

Hello, im making a custom level editor in my game and i have some questions. Currently i can edit position, rotation and scale values of objects when i click on them but i want to add custom parameters for specific types of objects .For example when i click on a vehicle it should show a speed value that can be editable, an explosive object should display explosion force and damage. Whats the best way of doing this without making spaghetti code?

knotty sun
deft hornet
knotty sun
rose harness
#

i have this script that is attached to multiple characters and there is a randomizer for that script

but that script will only output same randomized numbers for all the characters, how do i make it different output for each one?

knotty sun
deft hornet
#

why would i use it to create custom objects in my level editor

knotty sun
#

how do you expect to collect input?

deft hornet
#

inputfield

knotty sun
#

which is UI is it not?

deft hornet
#

yes

knotty sun
#

so why not UIToolkit?

deft hornet
#

whats the difference

knotty sun
#

UIToolkit is very much more flexible to create dynamic UI dialogs in code

lean sail
rose harness
#

the code is working fine, its just that im using the same script for all the characters

and this script is generating the random numbers same result for all the characters

#

so for example
player 1 has generated random numbers of 2 3 1 4
all other players has also 2 3 1 4

#

im using visual scripting if you can read that i can show

knotty sun
#

you probably want to use System.Random, where you can have a unique Random class instance for each character

lean sail
rose harness
lean sail
#

I assume your visual scripting stuff is creating a random instance with the same seed for each character which is why you get this issue

rose harness
#

how do i make different seed for each character?

rose harness
knotty sun
rose harness
knotty sun
#

you could use something like the instanceId of the character as the seed

swift falcon
#

what's a good way of structuring data?
for example: i have a Object1 class that has ObjectData1, but this Object1 can contain Object2 which needs ObjectData2 and maybe even a third Object
my approach is just having an initialise method in Object1 that takes in ObjectData2, but i feel like there has to be a better way to do it

knotty sun
swift falcon
#

i do make use of inheritance but i still need Object1 to have Object2 and its data

#

example:
Cells in a grid, each Cell can contain Land, and each Land can contain a Structure

knotty sun
#

then why doesn't Object1 inherit from Object2 ?

swift falcon
#

because i might want one to be able to exist without the other, a structure that doesn't need to be placed on Land in this example

knotty sun
#

then you need Interfaces

swift falcon
#

using this example, in what way would that be structured?

knotty sun
#

So your grid would be of type ICell
ICell would inherit from ILand
ILand would declare a Structure property
So any class which inherits from ICell must implement the ILand properties but can leave them null

#

you could do the same with abstract classes as well

swift falcon
#

hm ok i'll look into this more ty

lucid zealot
#

Hello, I need your help please. I work on a dialogue system based on this tutorial : https://www.youtube.com/watch?v=3LfpzaFqNsc. My text is invisible on screen but all my settings are good, I check my code, I don't see any error. I don't have error on my console. I never had sometimes like that and I don't see any report on internet for that. Can you help me please ?

NOTE: If you cannot see your character's text (dialogue or name) after applying a color to it, make sure that the alpha/transparancy of the color is set to 1! That's a sneaky thing I forgot to mention.

Let's take the customizations defined in our configuration file and apply them to the character's text appearance on screen

Video Resources:
Fo...

▶ Play video
gray mural
lucid zealot
#

the blue text is when I update the color but If I used the default settings I create it doesn't work

deft hornet
gray mural
lucid zealot
#

I create a scriptable object to set my settings. Then my Dialogue Manager get the chracter name " DL_Character character = DL_CharacterManager.instance.GetCharacter(speakerName);" based on the string name
then we get the config " DL_CharacterData config = character != null ? character.config : DL_CharacterManager.instance.GetCharacterConfig(speakerName);" and apply it on screen

#

I know that is this portion of code that doesn't work :
public void ApplySpeakerDataToScreen(string speakerName){

    //Get the name of the Character
    DL_Character character = DL_CharacterManager.instance.GetCharacter(speakerName);

    //Get the configs of this character (exist or default if don't exist)
    DL_CharacterData config = character != null ? character.config : DL_CharacterManager.instance.GetCharacterConfig(speakerName);

    //Apply the Color and Font
    ApplySpeakerDataToScreen(config);
}
novel bough
#

I have some sprite grids in the scene and zoom in and out functions using a camera, the issue is when I zoom out the sprites start to flicker and some parts disappear like half displayed(see video). please help to solve this.

gray mural
lucid zealot
#

I don't understand ^^'

gray mural
#

And I've mentioned sending code

this way
lucid zealot
#

My text is invisble on the screen but has color asign

#

I'm begginer in c# code so I don't understand all thos thing

gray mural
#

Sorry, haven't mentioned

lucid zealot
#

ah aha ok no problem ^^

gray mural
gray mural
#

I'm talking about your text in the scene

lucid zealot
#

I try to understand why my text is invisible because is apply

gray mural
lucid zealot
#

The position on axis ?

#

The position is good, is not a problem of hiding the message

mellow sigil
#

The color opacity is zero

lucid zealot
#

The message is displaying, it^s not a problem of color, z-index, set active or other. If I desactive this void :
public void ApplySpeakerDataToScreen(string speakerName){

    //Get the name of the Character
    DL_Character character = DL_CharacterManager.instance.GetCharacter(speakerName);

    //Get the configs of this character (exist or default if don't exist)
    DL_CharacterData config = character != null ? character.config : DL_CharacterManager.instance.GetCharacterConfig(speakerName);

    //Apply the Color and Font
    ApplySpeakerDataToScreen(config);
}

it show on screen but only in black

#

Oh fuck ! you are right ahahah

#

How ??

gray mural
lucid zealot
#

Thank you a lot ahah

#

You saved me 3 days of insomina ahaha

gray mural
#

I was thinking about the possibility of opacity being 0, but, for some reason, I thought black is 1 and white is 0.

lucid zealot
#

me too, I probably have a bug when I modify the color and I didn't realize it was pasing in 0 opacity because it was good at first

#

The color in code is coding like Color(red, green, blue, alpha) right ?
nameColor = new Color(nameColor.r, nameColor.g, nameColor.b, nameColor.a);

heady iris
#

That's the correct order, yes

#

note that these are in the [0..1] range (for non-HDR colors)

gray mural
lucid zealot
#

Ok so by default .a = opacity to 1 I don't need to specify that

#

Thank you, I'm learning

molten venture
#

I have a class A like so:

public class A{
  public List<Data> inputs = new List<Data>();
  public List<List<Data>> outputs = new List<List<Data>>(); 
}

I have a subclass of it like so:

public class B : A{
  public List<Data> outputData = new List<Data>();
  public B(){
  //Setting inputs
  //Setting outputData
  outputs.Add(outputData);
  }
}

Now, for some reason, when I save instances of B to a json file, inputs does appear while outputs not. What could be the problem?

gray mural
indigo verge
#

@latent latch "If you need data that can be assigned in the inspector"

Yeah, that was the general usecase, but I was running into situations where I needed both regular classes and SOs that can be assigned in inspector, such as having situations where character stats could be assigned via an SO template, but also generated during runtime using custom classes.

So I eventually ran into hiccups, where I was using SOs directly, for templates, but that locked me out of clean methods of using other class types, when I needed to go back and refactor my code for it.

thick terrace
molten venture
thick terrace
heady iris
#

nice (:

You mostly need GetComponent in places like physics messages (OnTriggerEnter, etc)

#

In those cases, TryGetComponent is really helpful

#
if (!collider.TryGetComponent(out Foo foo))
  return;

foo.Bar();
zealous lagoon
#

I maybe found some strange behaviour? I have 2 instances of the same class behing inherited by another class. The OnEnable on one of them does run, on the other it does not. The only real difference is that one sits as a child of a DontDestroyOnLoad object. Is this an intentional Unity feature or am I just messing up elsewhere?

heady iris
#

It returns a bool that tells you if it succeeded. The component gets written into the out argument

#
if (!hits[i].TryGetComponent<Entity>(out var target))
    continue;

if (target == entity)
    continue;

if (!target.TryGetModule<Grabbable>(out var grabbable))
    continue;

Grab(grabbable);

This is used to pick up an object. It does several checks in a row, including a TryGetComponent

#

(TryGetModule is really similar)

#

my entities have modules attached to them. they aren't necessarily on the same object, so I made a little system to keep track of all of them

#

I would still track that without using GetComponent

#

When you equip a weapon, store a reference to it in a field.

#

What's the rigidbody needed for?

#

The weapon component should contain a sprite.

thick terrace
zealous lagoon
#

Yes

#

I can quickly show code if neccessary

#

(its not much, like 10 lines)

#

Menu.cs

protected virtual void OnEnable()
    {
        SubMenu.ElementChosenEvent += OnElementSelected;
        Debug.Log(gameObject.name);
    }

    public virtual void OnElementSelected(int menuId, int subMenuId, int id)
    {
        Debug.LogWarning("Unimplemented OnElementSelected called.");
    }

SettingsMenu.cs

    public override void OnElementSelected(int menuId, int subMenuId, int id)
    {
        Debug.Log("Settings menu: " + menuId + " " + subMenuId + " " + id);
    }

SubMenu.cs

Debug.Log("Submenu:" + menuId + " " + subMenuId + " " + Locked);
ElementChosenEvent?.Invoke(MenuId, Id, id);

The SubMenu print is called, the print in SettingsMenu is not. The OnEnable in the Menu is not called for the SettingsMenu object. I have other Menu derived classes, and the OnEnable is called for them. SettingsMenu does not override the OnEnable

thick terrace
zealous lagoon
#

not in SettingsMenu

thick terrace
#

oh, never mind

heady iris
#

Right. You just display the sprite the weapon gives you

thick terrace
heady iris
#

If you need more than just a sprite, then I would give each weapon a prefab

zealous lagoon
#

Ok some new info, if I tick the box on and off in the inspector it gets called, it just doesnt get called the first time

heady iris
#

How do you pick up a weapon?

#

Do you have a separate "weapon pickup" class?

thick terrace
heady iris
#

Okay -- so what I would do is make the WeaponPickup component contain a reference to a prefab

#

When you pick it up, you instantiate that prefab and put it in a list of weapons you currently have

zealous lagoon
#

Uno momento, it seems to randomly disable itself in a frame

#

I guess that's the problem

#

just gotta figure out why the frick it happens

#

thank you for help tho

heady iris
#

Where does the actual shooting logic go?

sand gate
#

I'm trying to simulate a swerve drive robot in unity by using 4 WheelColliders and a RidgidBody. The entire chassis is super jittery and it moves in weird ways because of that. The other issue is it's insanely slow no matter how high of a number I set the rotation speed and motor torque. This is my code for controlling each module

public class SwerveModule : MonoBehaviour
{
    [SerializeField]
    private WheelCollider wheelCollider;

    [SerializeField]
    private Transform wheelTransform;

    [SerializeField]
    public float wheelAngleOffset = 0f;

    private float desiredAngle;
    private float desiredSpeed;

    public void setModuleState(float wheelSpeed, float wheelAngle)
    {
        desiredAngle = wheelAngle;
        desiredSpeed = wheelSpeed;
    }

    void Start()
    {
        desiredAngle = 0f;
        desiredSpeed = 0f;
    }

    void Update()
    {
        wheelTransform.localRotation = Quaternion.Euler(0, desiredAngle + wheelAngleOffset, 0);
        wheelCollider.steerAngle = desiredAngle;
        wheelCollider.rotationSpeed = desiredSpeed;
        wheelCollider.motorTorque = desiredSpeed * 10;
    }
}
#

this is how im determining what numbers to provide to the swerve module

    private void CalculateAndSetModuleStates(float vx, float vy, float rotation)
    {
        float A = vx - rotation * (robotLength / R);
        float B = vx + rotation * (robotLength / R);
        float C = vy - rotation * (robotWidth / R);
        float D = vy + rotation * (robotWidth / R);

        float[] wheelSpeeds = new float[4];
        float[] wheelAngles = new float[4];

        wheelSpeeds[0] = Mathf.Sqrt(B * B + D * D);
        wheelSpeeds[1] = Mathf.Sqrt(B * B + C * C);
        wheelSpeeds[2] = Mathf.Sqrt(A * A + D * D);
        wheelSpeeds[3] = Mathf.Sqrt(A * A + C * C);

        wheelAngles[0] = Mathf.Atan2(B, D) * Mathf.Rad2Deg;
        wheelAngles[1] = Mathf.Atan2(B, C) * Mathf.Rad2Deg;
        wheelAngles[2] = Mathf.Atan2(A, D) * Mathf.Rad2Deg;
        wheelAngles[3] = Mathf.Atan2(A, C) * Mathf.Rad2Deg;

        float maxWheelSpeed = Mathf.Max(wheelSpeeds);
        if (maxWheelSpeed > maximumSpeedMetersPerSecond && maxWheelSpeed > 0)
        {
            for (int i = 0; i < wheelSpeeds.Length; i++)
            {
                wheelSpeeds[i] = wheelSpeeds[i] / maxWheelSpeed * maximumSpeedMetersPerSecond;
            }
        }

        for (int i = 0; i < swerveModules.Length; i++)
        {
            swerveModules[i].setModuleState(wheelSpeeds[i], wheelAngles[i]);
        }
    }
#

Is a WheelCollider the wrong approach to this? And is the jittering from the suspension in the wheel collider being too stiff?

tough cradle
#

Hi yall, are the c# youtube tutorial any good?

steady moat
#

!learn is better

tawny elkBOT
#

:teacher: Unity Learn ↗

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

ashen pewter
#

can someone explain how to get children reference in unity toolkit hierarchy with script?

tough cradle
#

For some reason its stucked on downloading

heady iris
#

how do you know what gun the bullet came from?

tawny elkBOT
gray mural
# gray mural However, this does not seem to work. Nothing happens with the `Asset` when not r...

Hey, want to return to this question, as I wasn't able to fix it yet.
The Asset is a UnityEngine.Tilemaps.Tile and is not reset when changing its sprite manually in the Inspector.
This is not the case, however, when changing its sprite via the custom class, which holds it.

// public class TileSprite

[SerializeField] private Sprite _sprite;
public Tile tile;

public void Set(Sprite sprite)
{
    if (sprite != _sprite)
    {
        _sprite = tile.sprite = sprite;

        EditorUtility.SetDirty(tile);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
}

Tried to use as many methods as possible, but it doesn't seem to work properly now.

#

It seems that the Inspector saves the variable in the way not known to me yet

heady iris
#

I don't see anything that would cause GunShooting to get a new configuration after picking up a weapon

#

i don't understand how GunPickupAndThrow.EquipWeapon has any effect, really

#

especially since you've got all of these naked GameObject variables floating around

heady iris
#

well, it enables a sprite renderer

#

is GunShooting attached to each of these objects parented under WeaponSprites?

#

I see nothing in GunPickupAndThrow that even touches a GunShooting. How does the game figure out which GunShooting component to use when the player tries to shoot?

#

currentWeapon is private, so there can't be another component that does it

#

Player should have a field that stores the currently-equipped weapon.

#

Rename GunPickupAndThrow to WeaponHandling or something, and have it update that field when you pick up or throw a weapon

#

You could also do that (and change its type from GameObject to something more useful)

#

Part of the reason I've been pushing you to get rid of GetComponent is that it forces you to make your types more specific

#

GameObject doesn't really tell me anything when I look at it

#

it could be literally any game object

#

that's a given: everything "thing" in your game is a GameObject

#

It's more clear what your code is doing if it passes a Weapon, not a GameObject

#

i don't see how that's relevant to what we're talking about

#

I would get rid of that entirely. The weapon should have enough information to display the sprite and to set the shooting point

#

for example, it could contain a reference to a prefab

#

that prefab would have a WeaponVisual component on it

#
  • Rifle Visual <-- WeaponVisual
    • Shoot Point
#

Instantiate the prefab and attach it to the player when you equip the weapon. Destroy it when you throw the weapon away.

#

This way, you don't have to have every single weapon visual stapled to the player

#

and you aren't trying to look them up by exact name

#

Show me a screenshot of your player's hierarchy, with at least one weapon unfolded so we can see all of the individual objects

#

(you can alt-click to expand all children)

#

no, I want to see exactly what you're doing

heady iris
#

okay, that's simple enough

#

This will be a single prefab.

#

It will be referenced by every AM9 weapon in the game

#

When you grab the weapon, you instantiate that prefab and attach it to the player

#

This way, you don't need to have tons of weapon sprites stuck to the player

#

You also don't have to get the name exactly right

#

This also means that two different weapons can still use the same visual

#

The prefab should have a component on it. I'd call it WeaponVisual

#

it'll be pretty basic

#

in fact, it could just be:

#
public class WeaponVisual : MonoBehaviour {
  public Transform shootPoint;
}
#

When you instantiate the prefab, you'll get a WeaponVisual object.

#

You can then grab shootPoint from it

#

You can add more fields and logic to this component later, if necessary

#

then that's all the component needs to do!

#

Any time you're digging around in the hierarchy, consider replacing that with components that hold references to the things you need

#

I also have basically zero GameObject fields in my games

#

I only use a few, in places where I genuinely don't care what I'm referencing

#

(e.g. just moving an object to a position)

#

That would be more appropriate, yes

#

(every game object has a transform and vice-versa, so it didn't really matter there)

#

but Transform would better describe what the code is doing

swift falcon
#

I'm creating an airplane simulator and it has this piece of code:
rb.AddForce(transform.right * maxThrust * throttle);

here, maxThrust is set to 200f, throttle can be increased or decreased using space or shift.

The problem is; in flight if I reduce the throttle, the plane abruptly decreases its velocity. I want it to smooth over the change in throttling speeds over time and not abruptly.

How do I achieve it?

heady iris
#

You could pass the weapon to the GunShooting component when it gets equipped

#

GunShooting can then read information from the weapon

#

(or it can just store the weapon and get information from it as needed)

#

It would also need to know about the release point. I would pass that to GunShooting as well.

#

It sounds like you only have a single GunShooting component right now, and that it's on the player. Is that incorrect?

#

okay, so if you do that, then the player should call methods on the GunShooting component of whatever weapon is currently equipped

#

That is reasonable, yes

#

The weapon contains the component that makes the weapon fire

#

if the config is just a bag of data, it can be a regular C# class

#

add [System.Serializable] to it and it'll show up in the inspector

#

you can then put directly into the GunShooting component

#

No. I am saying that GunShooting should contain the configuration.

heady iris
#

the player should tell the weapon to fire

#

the weapon then decides what to do

#

Right. That component is responsible for picking up and dropping weapons (hence "handling")

#

Yes.

#

I wouldn't call it complex, but it's not trivial either. It makes you ask and answer some important questions about where your logic lives.

#

This is something you get better at as you design, implement, and re-design game systems

raw token
#

Can somebody help, when i try to drag and place an fbx file it wont happen

leaden ice
#

not into the scene view

raw token
raw token
#

ping me if you have a solution

leaden ice
# raw token

In the first place you are trying to draga blend1 file which is a blender backup file. Not supported really but wouldn't be harmful

In the second case pretty sure your project window is in a search mode of some sort. Open an actual folder inside Assets and drag it in there

raw token
leaden ice
leaden ice
#

the project window has a file directory on the left

#

you're in one of those "favorites" searches or something

#

which isn't an actual location

#

you need to open the assets folder or a subfolder of assets to drag stuff into

raw token
#

okay thanks ill try

#

thanks so much it worked

shell scarab
#

Anyone know how fast is a HashSet actually? Tried finding online but can't. For example if I had a HashSet of 5 items and a Span of 5 items, could it be quicker to loop through the span to check if an item exists every time?

vagrant blade
#

Those numbers are so very small that it would be of no consequence if it was faster to do it a different way, if you were to measure it.

modern creek
#

Don't optimize until you're experiencing a problem or unless your N is probably > 1m or so

#

for N of 5, either way is going to be insignificantly different

rigid island
#

How could I get the smooth movement of Rigidbody.velocity but the precision positioning of Rigidbody.position ?

When I do this the rigidbody goes insane,it does go to the correct spot after "settling", i tried also turning off gravity of each limb but didn't work..attached 1st gif

      while (Vector3.Distance(body.position, final ) > 0.1)
      {
          body.position = Vector3.MoveTowards(body.position, final,  120 * Time.fixedDeltaTime);
          yield return fixedUpdate;
      }

this one gives a nice smooth transition but isn't always precise. gravity is off in 2nd gif , but on 3rd

   while (Vector3.Distance(body.position, final ) > 0.1)
   {
       body.velocity = Vector3.MoveTowards(body.position, final,  300 * Time.fixedDeltaTime);
       yield return fixedUpdate;
   }```
leaden ice
# rigid island How could I get the smooth movement of Rigidbody.velocity but the precision posi...

Something like this?

while (Vector3.Distance(body.position, final ) > 0.01f)
{
    float maxSpeed = 300;
    float maxDistanceThisFrame = maxSpeed * Time.fixedDeltaTime;
    Vector3 diff = final - body.position;
    float actualDistance = diff.magnitude;
    float distanceToMove = Mathf.Min(actualDistance, maxDistanceThisFrame);

    Vector3 velocity = (diff.normalized * distanceToMove) / Time.fixedDeltaTime; // we want to move this distance in one physics frame.
    body.velocity = velocity;
    yield return fixedUpdate;
}```
#

there's probably a way to do it with fewer calculations but my brain did this as a first pass

#

This is more or less the calculation that MovePosition does, but by setting the velocity rather than using MovePosition

rigid island
#

genius with this lol

#

Thanks again! amazing

shell scarab
#

anyway yea someone gave me a benchmark and a span is like 1 nanosecond faster for 5 elements and 0.2 nanoseconds faster for 10, after that hashset takes over lol

modern creek
#

for 5 elements, the overhead is going to far outweigh your measurement, so it's not really correct and you shouldn't use it as your Truth

#

You should probably just use whatever API surface is nicer/cleaner/less error prone

unique delta
#

is there away to see static variables in inspector?

rigid island
#

they dont belong to any instance

somber nacelle
#

No, static variables are not owned by an instance of an object so it wouldn't make any sense to show them on instances

leaden ice
#

The class?

#

there is no such thing

#

You could always use a custom editor I guess - but why not just use the debugger

somber nacelle
#

You could technically write your own custom inspector for it to display the values on instances of the compinent, but what would be the point of that?

unique delta
leaden ice
#

The inspector really isn't a debugging tool, no matter how hard we try to make it one

heady iris
#

There's always OnGUI

quaint rock
#

would just log per frame or something, and collapse so if its the same it just stacks

#

or worse case a quick and dirty bit of UI that shows it

heady iris
#

I use OnGUI to show bits of information

#

my main project has a very elaborate debug menu that's all IMGUI based

unique delta
#

i m trying to transform a text in a string and i get this error: "Predefined type 'System.String' is not defined or imported"

vestal arch
#

use string instead of String

unique delta
naive swallow
tawny elkBOT
unique delta
#

is just this

#

i m using unity6 is there some new thing

vestal arch
frosty token
#

i'm using TMPro.TextMeshProUGUI usually

vestal arch
#

yeah that ^ is the class for the ui text component

unique delta
vestal arch
#

that doesn't answer my question

#

change the text of what? is it an element of the canvas

unique delta
#

yes is a text

heady iris
#

What is the error?

#

you should probably start there

vestal arch
#

is it Text - TextMeshPro

#

"yes is a text" doesn't answer my question

heady iris
#

TMP_Text covers TextMeshPro and TextMeshProUGUI. It is a parent of both types.

quaint rock
#

yeah i almost always use TMP_Text and can always set things fine

heady iris
heady iris
#

...huh

#

did you upgrade to Unity 6 Preview, or is this a new project created in 6 Preview?

quaint rock
#

is the error only in your ide?

heady iris
#

oh yeah, that's the first thing to consider

quaint rock
#

really sounds like its references are just buggered up

frosty token
#

I have this very odd problem where the rigidbody of the RaycastHit turns null after literally just passing a != null check, any ideas why this can happen?

if (Physics.Raycast(FirePoint.position, FirePoint.forward + inaccuracy, out RaycastHit hit, FireRange))
  {
      if (hit.rigidbody != null)
      {
          hit.rigidbody.AddForceAtPosition(FirePoint.forward * FireForce, hit.point, ForceMode.Impulse);
  
          if (hit.rigidbody.TryGetComponent(out Damage damage))
          {
              damage.TakeDamage(FireForce * 50f);
          }
          if (hit.rigidbody == null) { // this is true during debugging sometimes
              Debug.Log("hit.rigidbody is null??");
          }
          Debug.Log(hit);
          Debug.Log(hit.rigidbody);
          if (hit.rigidbody.TryGetComponent(out Human human)) // <!!! null exception on the rigidbody?
          {
              Debug.Log(human);
          }
      }
unique delta
#

i said that upthere

#

anyways do you have a ideea i tried lookin in the unity6 manula but can figure to find something

heady iris
vestal arch
heady iris
#

does it destroy an object?

frosty token
#

good point, checking that

#

it indeed Destroys but i was thinking because it happens at the end of the Update() it shouldn't matter, but it does

unique delta
quaint rock
#

feels like something is buggered up in them and having them regenerated could help

frosty token
#

i often get mixed up with the triggers and collision events, is it good practice to queue these and handle them in Update and FixedUpdate only?

deft torrent
#

Hello i need help, I try to do that my player slide on the wall :
if (isSliding == true)
{
rb.velocity = new Vector2(rb.velocity.x, Mathf.Clamp(rb.velocity.y, -wallSlidingSpeed, float.MaxValue));
}

I know that isSliding is true but my player drop on the floor normaly, my rb.velocity is false ? (the if is on void update)

frosty token
#

what about this?

if (isSliding == true)
{
    rb.velocity = new Vector2(rb.velocity.x, 0f);
}
#

(or actually i would try something like this:)

if (isSliding == true)
{
    rb.addForce(Vector2.up * -Physics.gravity, ForceMode.Acceleration);
}
sterile gorge
#

Hey folks, so I need to spawn an enemy but after a specified delay. How would you go about doing that? I have a coroutine that Im using currently with a yield new waitforseconds but I feel like that is a bit inefficient performance wise?

frosty token
#

That seems like a valid use of a coroutine to me. Also try looking into Awaitable, the syntax is nicer imo

leaden ice
#

Don't prematurely optimize

sterile gorge
#

Will do. Another question, i read that yield return new waitforseconds internally checks every time to see if the scaled time has passed but does that mean the thread is just waiting on this function?

leaden ice
#

No

#

It checks once a frame

frosty token
#

no threading unless you use the Job system of C#

leaden ice
#

If the thread was waiting the game would be frozen

sterile gorge
leaden ice
#

There nothing wrong with the coroutine

sterile gorge
frosty token
#

my general rule of thumb is, if you do things in Update or FixedUpdate especially, try to limit "heavy" calls like Coroutines and GetComponents etc, otherwise its pretty moot in terms of optimizing

sterile gorge
frosty token
#

if you are familiar with javascript, its the same "async", as in, it just keeps looping and checking a condition, if the condition is hit, it will continue, otherwise it will skip it, perform another Update ad infinitum

sterile gorge
#

Got it thanks!

leaden ice
#

Unity is single threaded unless you specifically create new threads or use the job system

sterile gorge
#

Got it thank you! Appreciate the help!

heady iris
#

Unity coroutines are -- if we strip out the special things like WaitForSeconds -- basically this:

#
List<IEnumerator> coroutines;

void Update() {
  coroutines.RemoveAll(coroutine => !coroutine.MoveNext());
}
swift falcon
#

i have an abstract Entity class, i want to instantiate a gameobject depending on the child class, is that possible somehow? a public abstract GameObject(); or something that i can overwrite in the child class

vestal arch
#

depending on the child class
would be the child class' responsibility then

swift falcon
#

okay so how would i implement that?

vestal arch
#

...normally?

swift falcon
#

sorry are you saying what i stated isn't possible to do within another class?

#

say a class that holds a list of entities and needs to instatiate them depending on which child class it is

vestal arch
#

no, im just not sure what you're stuck on, this just sounds like normal subclassing

vestal arch
swift falcon
#

like a public abstract GameObject GetGameObject();?

vestal arch
#

sure, might need to be virtual, not sure how c# deals with that exactly

swift falcon
#

right yeah ty i'll experiment 👍

heady iris
#

An abstract method is automatically virtual

quaint rock
#

yeah Abstract is virtual but has not implementation so it forces the extending class to implement it

lean sail
swift falcon
#

i have a separate object for data, EntityData

#

that's serializable

lean sail
#

Because overriding methods here doesnt really seem needed

swift falcon
#

wouldn't it save me from going if(Entity is EntityTypeA) Instantiate(EntityTypeAPrefab?

#

for every child type

lean sail
#

Because from what I understood, it looked like you were going to construct a new gameobject in that method (then likely add components). Unless a lot of the components added are conditional, I dont see why this cant just be a prefab

swift falcon
swift falcon
lean sail
#

I see, yes the base class can just have the field and every child class will have access if its public or protected

swift falcon
#

public abstract GameObject Prefab { get; }?

#

can't have a field on an abstract

quaint rock
#

that is not a field, its a property and you can have both virtual or abstract properties

swift falcon
#

yea ik i was saying i can't have it just be a field

quaint rock
#

ah my bad

swift falcon
#

all good

swift falcon
lean sail
swift falcon
#

oh true just don't mark it as abstract

quaint rock
#

think they meant you can not override it, but there is no need to override since you can just give it a new value in the constructor instead

#

since its just a field

#

if its really wanted to be abstract so the extending class "must" define it, yeah just use a get only property on the abstract side then do something like
public override int a => 5 on the extending side

swift falcon
#

right true that's probably better for my purpose

#

now i remembered one thing i was trying to solve but ended up sidetracked with: is initializing different Entities based on their EntityData, since EntityData is not an abstract or interface and all Entities have it
enums for each type is an obvious solution but is there a more elegant way of doing it?

quaint rock
#

also what do you want to differ in the extending class, like if its just a few field, and nots not how methods or properties work

#

why even go abstract

#

like if its all based on entityData and that is its own thing just sounds like you just want to construct things iwth EntityData passed in

swift falcon
#
{
    public abstract EntityData EntityData { get; }
    public abstract void InitialiseData(EntityData entityData);
    public abstract void Initialise();
    public abstract void Tick();
    public GameObject Prefab;
}```
this is the class rn does that answer the question or do you want me to explain the class's goal?
swift falcon
#

but i want to act on the data in different ways

#

and i might move on to making the data abstract too if i need to

quaint rock
#

what is EntityData type wise?

swift falcon
#

rn a Vector2Int and DataCollection which has two lists of data objects that are filled with different values depending on how they're initialised, so it's pretty modular

quaint rock
#

ok but on a regular C# class or Struct, or extending from MonoBehaviour or ScriptableObject

swift falcon
#

oh nothing

#

normal serializable class

quaint rock
#

ok so just make that non abstract and a field

#

you already have a to pass it in via the InitialiseData call

#

also would question if you want a whole new ENtity type for each of Entity data or not,

#

or is just have Entity be non abstract but difference instances setup with different data is enough

swift falcon
swift falcon
quaint rock
#

like you want everything to have EntityData so why have it abstract

#

its not like you need to change the implementation of how its got

#

not everything has to be abstract in a abstract class

#

also do not make guesses about what you will need in the future untill you have a concrete idea of what is needed then

#

just make stuff that works for current cases and is easy to understand

#

you can change it in the future if needed

swift falcon
#

true true

swift falcon
swift falcon
quaint rock
#

like maybe a good way is EntityData is a ScriptableObject and each EntityData type lives in your assets folder as a asset

#

then you can just use a serializedfield and drag on the one you want

swift falcon
#

yes it would be shared and changed a lot, scriptable objects wouldn't work in my case

quaint rock
#

why is that

#

otherwise really the option is to make all the EntityData's in some central place in code, and loop and pass it to each Entity that needs it

swift falcon
swift falcon
indigo verge
#
Part one: What happens when the battle scene first starts/opens?
  1. Scene starts
  2. Character Intros/Cutscenes
  3. Start someone's turn

Part two: What does a character's turn look like?
  1. Activate the AI Module of the character whose turn it is
  2a. Player-controlled AI open a UI to choose things.
  2b. NPC AI use their brains to choose things.
  3. Actions chosen are executed.
  4. When they're done, they can choose to end their turn, once their resources have run out, or for whatever other reason.

Part three: What does the overall combat state machine look like?
  1. Opening (When done, go to 2).
  2. Character Turns (Repeat over and over, switching between characters).
  3. Victory or Defeat (When victory or defeat conditions are met.

Are there any ambiguous parts here that I should plan out more clearly, for designing my turn-based combat system's state machines? Right now, I'm just doing the overarching planning, rather than the actual details.

elder citrus
unique edge
#

im trying to have an animation as a transition in a scene

#

and it works in other scenes

#

but specifically not this one

#

idk what to do

digital falcon
#
{
    _angle.y -= _lookAction.ReadValue<Vector2>().y * rotationSensitivity;
    RobitTools.ClampAngle(ref _angle, floorangleY);
}```
Trying to add a limit to how low the camera can rotate vertically but got hit with an error like this.
#

I'm unsure how to add in the floorangleY limit for ClampAngle.

somber nacelle
#

well it seems like this ClampAngle method you are using does not take 2 arguments

digital falcon
#

Yeah, I know. I'm trying to find a way for ClampAngle to take 2 arguements

unique edge
#

im so confused 😭

digital falcon
#

Or at least stop when a certain angle is reached.

somber nacelle
digital falcon
#

Overload?

somber nacelle
unique edge
#

Boxfriend can u help me with something?

#

it should be quick idk

somber nacelle
#

no

unique edge
#

ok

#

my bad

digital falcon
#

Huh

#

Can I overload even if all of my functions are floats?

#

Or do they needed to be doubles to make it work?

velvet pebble
digital falcon
#

Ok

vernal sphinx
#

Hey guys, I'd really appreciate some coding advice.

I want different audioclips played depending on what objects you click on.
Should I create an audiomanager and instantiate audioclips through it, or can I just add AudioSource to each of my gameObjects respectively and just use AudioSource.Play?

I'm asking in terms of better performance, I'm still a newbie so I don't know best coding practices

lean sail
vernal sphinx
lean sail
thin aurora
vernal sphinx
swift falcon
#

if i have an abstract Entity class with EntityData, and i want to spawn the correct Entity subclass depending on a variable in EntityData, what would be a good way do to that?

thin aurora
#

Can I ask what you are trying to do specifically that requires this?

swift falcon
#

i'm trying to spawn and initialise Entities from savedata, the savedata consisting of EntityDatas
a load function basically

turbid hazel
#

Hey guys someone an idea/hint?

leaden ice
#

Because it looks directly in the middle of the range aka about 0

#

And the way you're doing that Lerp it's not really going to exactly reach the desired values since it's a "wrong/lazy lerp"

vague rock
#

Guys, if I have an object which is inside a circle, how can I find the nearest point (to the object) that lies in the circle's circumference?

dusk apex
vague rock
#

yeah

dusk apex
#

Make a line from the center of your circle in the direction of the target with your circle's radius as the distance.

vague rock
#

what would be the target in this case?

dusk apex
vague rock
#

wait, so a line from the center of the object to the object?

#

ah

#

this always works?

dusk apex
#

Yes for circles and points

vague rock
#

ok, thx!

#

now to implement it...

dusk apex
vague rock
#

this should work, I believe:

#
Vector3 GetNearestPointInCircumference(Vector3 center, float radius) {
        Vector3 direction = transform.position - center;
        direction.Normalize();
        direction *= radius;

        return direction;
    }
#

you beat me to it 🙂

#

thx!

dusk apex
#

The answer would be a point on the circle's circumference nearest to the object's center.

vague rock
#

yeah

dusk apex
#

This would work for objects outside of the circle as well.
Do note though that you may get undefined behavior if the object is at the center of the circle - there isn't any direction if the object is at the origin of the circle (ideally, it would be equal distance from any point on the circumference of the circle)

vague rock
#

apparently it returns a position in the circle's circumference who's position is the origin

dusk apex
vague rock
#

sorry, the grey cube

#

on the left

dusk apex
#

Direction would be defined as (target position - initial position) normalized

vague rock
#

but it is?

dusk apex
#

So if the center variable was referring to the target, it would be (center - transform.position)

vague rock
#

let me try

#

the debug code, btw: ```csharp
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawLine(center.transform.position, GetNearestPointInCircumference(center.transform.position, radius));
Gizmos.DrawWireSphere(center.transform.position, radius);
Gizmos.DrawSphere(GetNearestPointInCircumference(center.transform.position, radius), 0.5f);
}

dusk apex
#

You may want to use local position if you aren't wanting to account for parental offsets

vague rock
#

but they are both children of root?

dusk apex
vague rock
#

yeah

#

I believe I have to add the center's position to the return

#

and use the original code (i.e. before inverting)

dusk apex
#

Yeah. The initial result did not account for the circle not being at the center of the world - you'd just add the circle's position as an offset to make it relative to the circle's position.

vague rock
#

do you mean gameobject or scriptable object

#

those are two different things (I believe)

#

oh

dusk apex
#

They're different tools used for different things.

vague rock
#

normally I'd split functionalities between different scripts

dusk apex
#

Where SOs aren't expected to be mutable.

vague rock
#

but if the game is small or has little functionality for each object, I think it's fine

dusk apex
#

And MBs are associated with GOs as components

vague rock
#

uhmmm, I think that is too much

dusk apex
vague rock
#

yes

leaden ice
#

This will become an unmanageable disaster in anything more complicated than flappy bird

#

Like I said, unmanageable disaster

heady iris
#

the entire point of components is that you can compose them

#

you can combine them to produce more complex behaviors

vague rock
#

Can unity show a dictionary in the inspector?

#

I'm asking because it isn't showing it to me

#

it's a dictionary of a enum to a struct

#

both have [System.Serializable]

rain junco
#

https://paste.ofcode.org/fH8srXsqbTMKs8sqryTqy2 so iam generating a area with blocks(stone) then changing them randomly and replacing them with ores(eachone has a start and end spawn height) but in the code when i rmove the waitforseconds(.3f) it spawns a kind of platform inone height only. And when i put the waittime it exits as it should

turbid hazel
vague rock
#

for the code I believe nothing should change if it's 2.809...e-9

heady iris
vague rock
#

oh

heady iris
#

There are "serializable dictionary" assets you can use

#

they're a bit jank from my experience

vague rock
#

I guess I gotta figure out another way to debug

gray mural
heady iris
#
public class IntFloatDict : SerializableDictionary<int, float> { }
#

e.g.

#

that was my experience when I used one of those packages, at least

gray mural
leaden ice
gray mural
late lion
gray mural
#

Dictionary contains a T for both key and value

#

So I don't think you can create one for it

vague rock
heady iris
#

I am very sure that I recently ran into a situation where it didn't work

#

so I'm confused in both directions!

gray mural
heady iris
#
public class Test : MonoBehaviour
{
    public EventPicker<GenericQualifiedFMODEvent, GenericQualifiedFMODEvent.Criteria> nuhUh;
}
#

enjoy my very long type names

turbid hazel
heady iris
#

i was expecting this to fail

#

this is 2023.2.20f1

gray mural
late lion
# gray mural No way. How have you done this?

What makes you think it doesn't work with more than 1 generic parameter? Generic serialization support was added back in 2020.1, and there were no limitations on the number of parameters then.

heady iris
#

I wonder if I got confused because I tried to serialize an abstract class

#
        public SecondOrderDynamics<float> oops;
#

yeah, that's an abstract class

#

of course it didn't serialize properly

heady iris
gray mural
late lion
#

Oh, well, I've only been talking about the support in the serializer. I'm not sure about custom editor support.

gray mural
#

Isn't that what a custom Editor is?

late lion
#

No. Custom editors decide how things get presented to the user, but can't change how things get serialized.

gray mural
late lion
gray mural
gray mural
#

Although not sure whether you can just use "MyClass" without the typeof keyword for generics

late lion
gray mural
#

Unity doesn't support it, I suppose

late lion
#

If you have no custom editor, are you seeing the default inspector for your type?

late lion
#

If you see nothing, that doesn't mean the custom editor isn't working, it means the serialization isn't working. Because Unity will always display anything that is serialized with a default inspector.

heady iris
#

Components can't have a generic type. They need to be a concrete type.

late lion
#

Oh, right. That's my bad. I thought you were using a property drawer.

gray mural
#

Unity doesn't serialize generic classes with the Serializable attribute

gray mural
vague rock
#

the struct one

#

I believe is easiest, right?

late lion
# gray mural No?

I'm confused now. Are you making a CustomEditor for a MonoBehaviour, or a PropertyDrawer for a serializable class? You can't make a CustomEditor for a serializable class.

heady iris
#

yes, those are two totally different things

gray mural
vague rock
#

and create a list of it?

gray mural
#

This is an example I've taken from my code

[Serializable]
public class TileSpriteInfo
{
    public TileSprite sprite;
    public string name;

    public TileSpriteInfo(TileSprite sprite, string name)
    {
        this.sprite = sprite;
        this.name = name;
    }

    public override string ToString() => $"({sprite}; {name})";
}
gray mural
vague rock
#

ok, thx!

heady iris
#

I do something similar to save my game settings

#
[Serializable]
public class FloatSettingValue
{
    public FloatSetting setting;
    public float value;
}
#

I could actually serialize dictionaries with Json.NET, but this wound up being more conveinent anyways

gray mural
heady iris
heady iris
#

a CustomEditor is used to create a custom inspector for a unity object

gray mural
#

I see, this class is serialized properly

[Serializable]
public class Test<TKey, TValue>
{
    public TKey foo;
    public TValue bar;

    public Test(TKey foo, TValue bar)
    {
        this.foo = foo;
        this.bar = bar;
    }
}
heady iris
gray mural
#

For some reason, I thought it was impossible since it's not possible with the custom Editor

vague rock
#

is tuples serializable?

#

or will I need to create another struct?

heady iris
leaden ice
vague rock
#

ahhhh

#

whyyy

serene stag
#

How to remove Gradle error.

trim schooner
serene stag
#

I fixed it but when build it's giving the same error dialog box in unity.

hexed pecan
heady iris
#

FloatSetting is a NamedIdentifiable, which is an Identifiable, which is a ScriptableObject

#

Identifiable copies its asset GUID into itself

#

I have a custom converter for Json.NET that serializes an Identifiable as its GUID

#

To deserialize, it asks the IdentifiableRegistry to give it the object that corresponds to the GUID it just read

#

I load all of the relevant objects into the registry on game start

#

the serialized float settings look like this

#
        {
            "setting": "746195CFEFACF4F21B28F1B7582420E6",
            "value": 80.0
        },
        {
            "setting": "62774F12EDF4B4363BEAAFF33E1B04BA",
            "value": 1.0
        },
        {
            "setting": "C7BDEBFD74B7F4747A85D455C77E22BC",
            "value": 0.4
        },
vague rock
#

guys, my vscode isn't formatting some unity code

#

where can I ask about it?

heady iris
#

Some code?

vague rock
#

ok!

pastel halo
#

Hey, I'm having some difficulty cloning an instance of an arrow prefab.
I've tried a few things but it still doesn't work.

I've tried directly referencing the field, but that adds the component to the original prefab, since usedArrow = newArrow, and doing addComponent directly alters the original instead of an instance.

I've also tried creating an instance then turning it off, but the code seems to break because the arrow self-destroys even when disabled (has ontrigger event/coroutine on start). Meaning the "created template" gets self-destroyed before it can be used by the bowObject. Plus it tries to execute the arrow as if its a normal arrow, rather than a template in memory.

What I'm trying to do is create a prefab object in memory, where it can be used as a reference rather than a scene object which executes. I want to clone the original, then modify the newly created object, then inject that into a field which the bowObject will then use as the "real arrow". The bowObject will never reference the original prefab, only the modified one which is created at runtime.

The idea is that when you level, you get different perks that get applied to the arrow. The idea was to avoid creating a ton of prefab variants with custom scripts on it, and instead make these modifications to a clone at runtime when something like a LevelUp() or OnStart() event is called.

Additionally, the reason for having a custom field is to avoid spamming addComponent everytime an arrow is created, and instead grab from the modified template, so this operation is only called once. Meaning all the heavy lifting is done initially in CreateArrow() then the field is just referenced

Any ideas on how to create a copy of a pre-existing prefab in memory, modify it, put it in a field, then reference it, all without spawning it in scene? ChatGPT seems to suggest the "instantiate then disable" but then you only spawn disabled arrows...

dusk apex
pastel halo
#

is instantiation the only way to create a template? Or is there another method to safely create a copy in memory only?

heady iris
#

Instantiate is how you copy a unity object.

#

There is no other way to do so.

pastel halo
#

when i say template, i mean copy over the rigid body, collider, the script and any other info from the original object which would be spawned in scene

dusk apex
#

Sounds like you're wanting to create a new instance of the prefab, which is what instantiate does. You aren't wanting it in the scene which implies you'd want it not active.

pastel halo
#

but can instantiate be ran without spawning something in scene?

heady iris
dusk apex
#

Then you'd just copy/clone the instance and have the clones be active etc

pastel halo
#

Ya I am, i seem to be misunderstanding something. Since when i instantiate and modify it, it'll try to execute the code.

Even when I do instantiate the arrow and turn everything off/disable it, for some reason when I spawn a bunch of disabled arrows, when I touch one the reference arrow gets destroyed and the bow fails to see any arrow

#

something strange is happening

knotty sun
#

you know you can modify the prefab before Instantiating it and the new clone will have those modified properties

pastel halo
#

Ok, it sounds like the only way to create things is to actually spawn them in scene, then turn them off, so that it physically exists as a reference

heady iris
#

Set each arrow up the way you need is as you create it

#

I guess it'd be nominally more efficient

dusk apex
pastel halo
#

Ok, sounds like i have a redundant field based on what ya'll are saying which makes sense

#

I'm trying to avoid operations like spamming add component every time a bullet or arrow is fired. maybe it has 12 components per arrow or 50, i'm not sure. but the idea was to create it once then reference that new modified arrow

#

is add component cheap?

heady iris
#

Additionally, the reason for having a custom field is to avoid spamming addComponent everytime an arrow is created, and instead grab from the modified template, so this operation is only called once. Meaning all the heavy lifting is done initially in CreateArrow() then the field is just referenced

A few AddComponent calls are completely fine. I'd rather have that than deal with the oddities of trying to make "fake prefabs"

dusk apex
#

Just create variants for your prefab if the components differ else modify fields and whatnot of the new instance on spawning.

heady iris
#

it sounds like there would be a very large number of prefab variants

#

e.g. 10 components, pick any number of them

pastel halo
#

yes, i'm trying to forward think so i don't get boxed in

#

it's just there's some technical strangeness with the methodology that i'm trying to work out

#

I'm following the suggestions, just trying to confirm it. because ya add component everytime instantiate is called would be easiest

#

I usually do mod = Instantiate(something, transform), then mod.DetonateObject(5); etc etc

dusk apex
pastel halo
#

ok sec, gonna modify my current code to remove the redundant field

#
       [Header("Template")]
       public Projectile arrowTemplate;
       public Projectile usedArrow;

       [ContextMenu("Create arrow")]
       public void CreateArrow()
       {
           // Take template, then adjust, then set as active arrow
           var newArrow = Instantiate(arrowTemplate);
           newArrow.enableArrow = false;

           // add ricochet spell to arrow 
           var comp = newArrow.AddComponent<RicochetArrow>();
           comp.SetProjectile(arrowTemplate);

           // assign the template reference...
           usedArrow = newArrow;

           Debug.Log("Updated arrow with new stats!");
       }

#

the bow object just uses a getter function which returns "usedArrow" so it knows to use the runtime version of it

#

The bow just calls this

            projectile = PlayerEquipment.Instance.GetArrow();
            Instantiate(projectile, TransformsManager.Instance.arrowLoc.position, 
dusk apex
pastel halo
#

at the moment yes, it was just a test

#

i would have a switch that picks what component stack to add once i create that code

dusk apex
#

Assuming you aren't hard coding this for every combination, maybe just create a prefab with the component already attached?

pastel halo
#

thats what i wanted to avoid because i don't know how many components i will have

#

i wanted to automate that

heady iris
#

If you can't meaningfully set up the arrows ahead of time, then I'd just go ahead and use AddComponent each time

#

Especially since this isn't going to be happening dozens of times per frame

#

I can't imagine that AddComponent is that much worse than instantiating something with the component on it already, either

pastel halo
#

true, the AC would be once on creation. if its relatively inexpensive thats the go to

#

but to confirm, you must instantiate an object turned off in order to create a template that can be referenced?

heady iris
#

there's nothing special about it being turned off

#

you can instantiate whatever you want

pastel halo
#

I believe that makes sense in the context of mono. since mono objects must be attached to physical game object

heady iris
#

if you want to prevent Start from running, the relevant behaviors must be disabled

#

or the entire game object must be deactivated

pastel halo
#

ofc, i placed the actual code in a function ActivateArrow() and put a bool return on the onTriggerEnter to prevent the arrow from activating (has to be manually activated)

#

ya i did a enabled = false but ontrigger enter seems to run, but when i added a !isActive bool it blocks that strangely enough

#

i do cache the instantiates into a local variable then modify them for sure, it just seems to be acting up here and there for some reason

#

but it sounds like I have two options, and indeed I do need to instantiate (there is no non scene instantiate operation like new() that would put it in memory)

dusk apex
#

Just have the object inactive?

pastel halo
#

yep i get that, just confirming at this point

dusk apex
#

Enable would only be referring to the specific component

pastel halo
#

true, i've done both. enabled = false and gameobject.SetActive(false)

#

i'm tellin ya something is off on my end. but thanks for the info just wanted to confirm the options

#

btw, why doesn't new() work?

heady iris
#

new what?

pastel halo
#

From what i've tested, it just creates a new class object, but it doesn't create an actual prefab in memory like i was hoping

#

like var arrow = new Projectile(); arrow.ActivateProjectile(5) for example

heady iris
#

You are not allowed to construct new Component objects