#archived-code-general

1 messages · Page 51 of 1

leaden ice
#

Every pixel on the screen corresponds to a whole ray of possible points

#

At varying distances from the camera

swift falcon
#

I want it at whatever depth the 2d grid exists, probably that's why you suggest Plane.Raycast

leaden ice
#

Yep exactly

hollow stone
#

You just answered yes when asked "Is the position way off?" and that it's " a little to the left?". You're really not making it easy to understand you x)

#

So you have two problems then.

swift falcon
#

yes

#

I can't adjust the Lock Color, no?

#

so can't change the color

hollow stone
swift falcon
#

yeah

#

what about it?

hollow stone
#

Huh, they hide the info for some reason.

swift falcon
#

I suppose I can just unlock color in code

hollow stone
#

Yeah you can do that, or make a new tile type for it that lets you show it in inspector.

swift falcon
#

even with none tile it doesn't let you set Lock Color though

hasty haven
#

How do you like my save file? lmao

fiery fractal
swift falcon
#

why's everything red anyway?

potent sleet
dusk apex
swift falcon
#

ah cool, agreed, bit strong for my taste though

coarse gull
#

is it possible to enable momentum for the built-in character controller?

rain minnow
coarse gull
#

Alright thanks. That might've been a stupid question btw

#

I'm just new to unity

somber nacelle
#

namespaces are used to help organize your code. if you find that your code is more organized and the namespaces make sense and that they contain related objects then you're using them correctly

leaden ice
#

Kinda looks like you're making namespaces just for individual classes which seems excessive

somber nacelle
#

keep in mind that not everything needs to be in a namespace, there's nothing wrong with having classes that don't really fit in other namespaces just directly in the root namespace

fiery fractal
valid estuary
#

Is there a way to appenbd a string Prefix to a variable?

I'm messing around with blendshapes
they all have a prefix

    public string prefix = "SFB_BS_";
    public SkinnedMeshRenderer SMR;```

What i want to do is 
SMR.SetBlendShapeWeight(prefix & ArmMusclePlus, (float)CC.ArmMuscleMinusSlider.value);

So it get the value of the slider from script CC and updates it on this script so they match.
Its entirely possible im missing something really stupid:
hollow karma
#

hey people

#

I'm adding a walljump to my 2d platformer character

#

and for the most part it works well

#

there is one problem though

#

im using physics.checksphere to check if my player is on a wall

#

and the onyl way I can explain my bug is if physics.checkpshere runs in fixed update

#

so if the player quickly gets on a wall and tries to jump off before the next fixedupdate cycle

#

nothing happens

#

im gonna try using a collider, and ontriggerenter

kindred sparrow
#
using System.Collections.Generic;
using UnityEngine;
public class FlowerPicking : MonoBehaviour
{
    public float interactionDistance = 5;
    GameObject temp = GameObject.Find("Humanoidblock");
    Transform HumanoidblockTransform = temp.transform;
    void Start()
    {
        
    }
    void Update()
    {
        if(Humanoidblock.transform.position.x >= transform.position.x+ interactionDistance && Humanoidblock.transform.position.x <= transform.position.x + interactionDistance && Humanoidblock.transform.position.y >= transform.position.y + interactionDistance && Humanoidblock.transform.position.y <= transform.position.y + interactionDistance)
        {
            Debug.Log("FlowerDetected!");
        }
    }
}

This might be a stupid error, but I've been staring at this for too long. Why does Humanoidblock not exist in this context? It is another cube on the game I'm making.

valid estuary
#

Add something like this to update

#

if (Humanoidblock !=null {do the stuff} else return;

#

find is slow

#

so this way you are giving it n out when it takes too long

#

Also you should probably pu this: GameObject temp = GameObject.Find("Humanoidblock");

#

in start

#

and change the top to Gameobject temp;

kindred sparrow
valid estuary
#

you put that in defines, its not going to execute the find there

#

so it will remain null because nothign exists there

kindred sparrow
#

Im sorry, what is 'defines'?

#

Im new to coding

valid estuary
#

its the place where you put all your variables

#

public float interactionDistance = 5;
GameObject temp = GameObject.Find("Humanoidblock");
Transform HumanoidblockTransform = temp.transform;

#

thjis part

#

you are telling the script (defining) that these values will be used

kindred sparrow
valid estuary
#

Here is how i would do it

gray zephyr
#

Facade pattern my beloved

#

(Is the facade pattern acceptable in Unity development? Lmao) /gen

valid estuary
#
using System.Collections.Generic;
using UnityEngine;
public class FlowerPicking : MonoBehaviour
{
    public float interactionDistance = 5;
    GameObject temp;
    Transform HumanoidblockTransform;
    void Start()
    {
        GetTempGameoObject()
    }
    void Update()
    {
if (temp != null){
        if(Humanoidblock.transform.position.x >= transform.position.x+ interactionDistance && Humanoidblock.transform.position.x <= transform.position.x + interactionDistance && Humanoidblock.transform.position.y >= transform.position.y + interactionDistance && Humanoidblock.transform.position.y <= transform.position.y + interactionDistance)
        {
            Debug.Log("FlowerDetected!");
        }
    }} else return;

}

public void GetTempGameoObject() 
{
    GameObject temp = GameObject.Find("Humanoidblock");
    Transform HumanoidblockTransform = temp.transform;
}```
#

So this way you are telling it that those will be filled in.
When Start runs it does the new function GetTempObject where it fills those values in for you

kindred sparrow
#

Thank you

valid estuary
#

AND in update it makes CERTAIN those have a value or it does nothing

kindred sparrow
#

alright

#

My flower picking code development can now continue!

#

:>

valid estuary
#

you could also set it up to else then run the command again

#

its ur choice

kindred sparrow
#

?

#

What do you mean by that

valid estuary
#

Well if its null its skips the update

#

so if its null then it quits the function, so in stead of return; you could add this instead:

#

else GetTempGameoObject() ;

kindred sparrow
#

It needs to always be detecting the humanoids movement

valid estuary
#

this way if see its null then it trys again to fill the variables

#

now you have 2 safe guards that it will work

#

Make sense?

kindred sparrow
#

Yes

valid estuary
#

Also disregard my question above....I need to use a index value for my Blendshapes....becuase apparently unity is too dumb to use a string instead of an int to let me modify it, that seriously needs to be changed to let us use either, cause thats really stupid and inconviennt when youv got 75 Blendshapes to alter

valid estuary
gray zephyr
#

Basically when something looks neat and presentable on the outside (like a single Method) but underneath the surface it's a mess (the actual body of the method)

#

Ah yes,
MyMonoBehaviour.MoveThing() but it's secretly 12 lines of indecipherable transform = ... and transform.rotate = ...

valid estuary
#

Ah ok. That makes sense

#

so I guess i do technically use it >_> by virtue of making it readable

#

thx for clearing that up for me!

kindred sparrow
#

im going to eat my computer

valid estuary
#

1 moment please

#

I wrote that i just didnt use my api.

earnest gazelle
#

Dudes, do you know nav mesh generator for voxels? a tool for it, generate nav mesh for 3d voxels/grids

valid estuary
#

Here we go, no more red

#
using System.Collections.Generic;
using UnityEngine;
public class FlowerPicking : MonoBehaviour
{
    public float interactionDistance = 5;
    GameObject temp;
    Transform HumanoidblockTransform;
    void Start()
    {
        GetTempGameoObject();
    }
    void Update()
    {
        if (temp != null)
        {
            if (temp.transform.position.x >= transform.position.x + interactionDistance &&
                temp.transform.position.x <= transform.position.x + interactionDistance &&
                temp.transform.position.y >= transform.position.y + interactionDistance &&
                temp.transform.position.y <= transform.position.y + interactionDistance)
            {
                Debug.Log("FlowerDetected!");
            }
            else GetTempGameoObject();
        }

    } 
    public void GetTempGameoObject()
    {
        GameObject temp = GameObject.Find("Humanoidblock");
        Transform HumanoidblockTransform = temp.transform;
    }
}```
#

that was my bad, I should have checked the formatting first

#

So the big error you had was Humanoidblock.transform.position.x >= transform.position.x + interactionDistance

But since we made it smaller by cacheing it instead of using the object you were looking for, you needed to justr set it to temp since thats your gameobject

kindred sparrow
#

unity is yelling at meee

valid estuary
#

copy paste the code i just gave you.

#

its a teeny bit different

kindred sparrow
#

:o

valid estuary
#

Thing is im not sure which variable to give you for the update block

#

its either temp or HumanoidblockTransform

#

I think either would work honestly

#

if one doesnt work just swap it out

#

for the other

kindred sparrow
#

Alright thank you

#

there isnt an error anymore

valid estuary
#

there ya go ;)

#

sorry i confused ya by being lazy this is what i was working on a few moments ago:

#

so yea i was being lazy so my baddd

plucky karma
#

Create a ILimb interface that contracts SetDisplayText() method, then create a class per each limb, e.g. Arms, Shoulders, that inherits ILimb interface. Then you'd access the class by referencing the interface it provides, and invoke SetDisplayText() method.

somber nacelle
swift falcon
#

Can events not be called from the animation events?

potent sleet
swift falcon
#

Even though debug logs show that it is being called and it exectues.

#

I checked the event calling in a different way, and it did work correctly.

potent sleet
swift falcon
#

I'm completely lost at this point, I tried several different things

potent sleet
#

post relavent code !code

tawny elkBOT
#
Posting code

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

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

swift falcon
#

gimme a moment, I'll do that

potent sleet
#

ok I gotta run out real quick, but I'm sure someone here has a solution for you

swift falcon
#

thank you

#

here's the relevant script

swift falcon
#

Should probably mention that calling something like this seems to work, even if I do it in the same script.

float radius = 10f;
float force = 100f;
int layerMask = 0;

EventManager.ExplosionInvoked(position, radius, force, layerMask);```
#

It just doesn't seem to like it that I'm calling from an animation event that's being triggered on timeline of character.

wispy wolf
#

That doesn't do what I want though. Say my velocity is (4, -1, 0), the other normal is (0,1,0), and the force is 5. The desired result would be (4, 5, 0) so any velocity perpendicular to the normal is preserved.

cosmic rain
#

Take a screenshot of your animation event setup.

swift falcon
#

StompImpact for some reason doesn't even come up, so I have to use StompLand()

#

@cosmic rain ^

cosmic rain
#

What if you make it public?@swift falcon

#

Aah, I see. Ite because of it's parameters.

#

But either way, you don't invoke any events in any of these methods.

swift falcon
#

making them public didn't work

#

I thought you would invoke the event whenever it's called and broadcasts the parameters

cosmic rain
#

Animation events can only have no parameters or one parameter of a simple type like int afaik.

swift falcon
#

Yeah, but since my "StompLand" looks like this ``` private void StompLand()
{
StompImpact(charFoot.transform.position, charStats.charJumpForce * 15f, charStats.charAOE, combatLayer);
}


Shouldn't it be invoking it?
cosmic rain
swift falcon
cosmic rain
swift falcon
#

thunk isn't invoking just executing the method with parameters?

#

Since my event script contains ``` public static void ExplosionInvoked(Vector3 position, float radius, float force, int layerMask)
{

    ExplosionEvent?.Invoke(position, radius, force, layerMask);
}```
cosmic rain
swift falcon
#

Yes, but it doesn't seem to be broadcasting anything

#

Or does one call it differently to broadcast?

cosmic rain
#

What isn't broadcasting anything?

#

What is supposed to be broadcasted?

cosmic rain
swift falcon
gray zephyr
#

Strategy Pattern my beloved

cosmic rain
#

No. You'd call EventManager.ExplosionInvoked(params) if you wanted the Event manager to invoke the event.@swift falcon

swift falcon
#

I see, it worked! Now to find out what stupid thing I did to overload my system lmao

#

@cosmic rain thank you

cosmic rain
leaden ice
#

what other normal?

#

and wdym by force in this context?

#

From your original description you had:

  • A direction you wanted to go (the normal)
  • A speed you wanted to go in (the "force") right?
    So the answer is direction.normalized * speed
#

unless I'm missing something - maybe you could draw a picture?

acoustic kayak
#

Hey guys, I'm having an issue and it's frying my brain. I have a EquipmentController class, which is used as a base for a bunch of different Equipment and within it, a function 'Click' gets called which does a fairly simple GetInventory().addItem(this.gameObject);, after which calls a SwitchSlot() function inside my InventoryManager.

In the InventoryManager, I have a function like this:

    public void SwitchSlot()
    {
        int currentIndex = -1;
        for (int i = 0; i < inventoryItems.Count; i++)
        {
            if (inventoryItems[i] == GetItemCurrentlyHeld())
            {
                currentIndex = i;
                break;
            }
        }
        if (currentIndex == -1)
        {
            currentIndex = 0;
        }
        if(inventoryItems.Count == 0)
        {
            return;
        }

        int nextIndex = (currentIndex + 1) % inventoryItems.Count;
        List<GameObject> swappedItems = new List<GameObject>(inventoryItems);
        GameObject currentItem = swappedItems[currentIndex];
        GameObject nextItem = swappedItems[nextIndex];
        swappedItems[currentIndex] = nextItem;
        swappedItems[nextIndex] = currentItem;

        if (currentItem != null)
        {
            EquipmentController currentEquipment = currentItem.GetComponent<EquipmentController>();
            currentEquipment.gameObject.SetActive(false);
        }

        if(nextItem != null)
        {
            EquipmentController nextEquipment = nextItem.GetComponent<EquipmentController>();
            nextEquipment.gameObject.SetActive(true);
        }

        inventoryItems = swappedItems;
    }

However, it seems that when I pick up more than two equipment pieces, the third one completely gets ignored. When I debug the inventoryItems, I do see it sitting at the end of the array.

#

My GetItemCurrentlyHeld() function is simply this:

    public GameObject GetItemCurrentlyHeld()
    {
        foreach(EquipmentController gObj in GameObject.FindObjectsOfType<EquipmentController>())
        {
            if (gObj.isActiveAndEnabled && gObj._isPickedUp) return gObj.gameObject;
        }

        return null;
    }

Which I do believe is resolving correctly.

ocean quail
#

Is the SwitchSlot function just meant to... You have a list of InventoryItems<GameObjects>
You'e added the newest item to the end of the list.
You then...swap the newest item with your current item, and put the current item at the end of the list?
Then then disable the currentItem and enable the new item?

acoustic kayak
#

Okay, after you said that I realized how dumb my idea was in my head. I re-wrote it and now it's this:

    // Switch the slot to the active item.
    public void SwitchSlot()
    {
        // If there's no items in the inventory, return and stop trying to switch slots.
        if (inventoryItems.Count == 0)
        {
            return;
        }

        // Get the index of the currently active item.
        int currentIndex = -1;
        GameObject currentItem = GetItemCurrentlyHeld();
        if (currentItem != null)
        {
            currentIndex = inventoryItems.IndexOf(currentItem);
            currentItem.SetActive(false);
        }


        // Calculate the index of the next item in the inventory.
        int nextIndex = (currentIndex + 1) % inventoryItems.Count;

        // Get the next item in the inventory.
        GameObject nextItem = inventoryItems[nextIndex];

        // Deactivate the currently active item.
        if (currentItem != null)
        {
            EquipmentController currentEquipment = currentItem.GetComponent<EquipmentController>();
            currentEquipment.gameObject.SetActive(false);
        }

        // Activate the next item in the inventory.
        if (nextItem != null)
        {
            EquipmentController nextEquipment = nextItem.GetComponent<EquipmentController>();
            nextEquipment.gameObject.SetActive(true);
        }
    }

Not doing any manipulation to the array anymore, however it seems like sometimes it'll pick up the equipment and not hide the rest.

ocean quail
wispy wolf
# leaden ice unless I'm missing something - maybe you could draw a picture?

I got it working the way I'd like, but it is undoubtedly inefficient.

Basically the goal is to take a Vec3 and set it's magnitude along an arbitrary normal to a force value without changing any perpendicular values.

So what I got is this:


Vector3 initialVelocity = someObject.velocity;
Vector3 perpendicularInertia = initialVelocity - Vector3.Project(initialVelocity , transform.up);
Vector3 targetVel = perpendicularIntertia + (transform.up * force);

So by projecting the other object's velocity along transform.up (which can be any direction at all, not necessarily world up) I can get the velocity of the object in the direction I'm going to set later. Subtract this from initialVelocity and I'm left with the velocity on the other axes untouched and the velocity in the direction of transform.up is now zero.

Then I can directly set the velocity along transform.up by adding that normal multiplied by whatever the force is.

So the velocity perpendicular to the transform.up normal is unchanged, but parallel to transform.up can be directly set to whatever value I want.

gray zephyr
#

this = ...
Cursed code

tiny delta
#

Is there any way to make a class with static variables that can be modified from the Assets folder - kind of like a static ScriptableObject?

leaden ice
#

so you're kind of mixing metaphors here

#

and it's unclear what you want

tiny delta
#

I just want a class for "default stats", which a character script can access when instantiated. However, I am trying to do this so that I could change any of the fields in "default stats" by clicking on the script in the assets folder and changing it in the inspector.

#

If that's not possible, I'll just put it as a monobehavior in a GameObject with the statics and an Awake trigger to set it from a serialized field

leaden ice
tiny delta
#

Right, but the ScriptableObject can't be accessed from an object within a script, right? (outside of using strings to search the assets folder) I'd have to drag and drop it onto the new object which isn't possible because it is instantiated

leaden ice
#

not an issue

tiny delta
#

🤦‍♂️ I'm just dumb

acoustic kayak
# ocean quail When you say "pick up the equipment" what lines of code are you referring to?
    [PunRPC]
    public void Click()
    {
        // Ensure that the player cannot pick up more than the x amount of items.
        if (GetInventory().GetAmountOfHeldItems() >= GetInventory().GetMaxAmountOfHeldItems())
        {
            return;
        }

        // Get the Hand Cube each time. At one point this caused a target invocation issue with Rpc if it wasn't here.
        handCube = GameObject.FindGameObjectWithTag("RightHand");

        // Ensure that the item clicked on is owned by the person attempting to click it.
        _photonView.RequestOwnership();

        ShowHand(true);

        // Marking this item as picked up, 'adding' it to our inventory list.
        _isPickedUp = true;

        // Setting the parent, position and rotation to our handCube, which is the player's right hand.
        transform.parent = handCube.transform;
        transform.position = handCube.transform.position;
        transform.rotation = handCube.transform.rotation;

        // Using our offsets defined earlier to locally position it to match the players' screen.
        transform.localPosition = new Vector3(offsetX, offsetY, offsetZ);
        transform.localRotation = Quaternion.Euler(rotationX, rotationY, rotationZ);

        _photonView.RPC("SetBoxCollider", RpcTarget.AllBuffered, false);
        _photonView.RPC("SetRigidBody", RpcTarget.AllBuffered, true);

        this.tag = "HeldEquipment";
        
        // Used for cross-referencing to ensure that this is the active item in hand for Inventory.
        _isHeld = true;

        // Add this item to Inventory Slots
        GetInventory().AddInventoryItem(this.gameObject);

        // Run the rest of any click code there is per-equip.
        ClickEquipment();

        // Switch inventory slot to currently held item.
        GetInventory().SwitchSlot();
    }
errant grove
#

Hello, question about Unity Localization:
How can I get get localized string from static class only using key?

gray zephyr
#

Design patterns are hard atomize

valid estuary
# plucky karma Create a `ILimb` interface that contracts `SetDisplayText()` method, then create...

Nope, This case it would be useless its just a character creator theres no need to do that extra work. Gonna be used in one scene and only 1. If i did all that it would actually make it way less efficient. This way the compiler and API know exactly whats going on. And its just faster for me, flat out. I don't mind going out on a limb to learn something new when it would make sense to apply that. But in this case there just no need.
Keeping it Simple.

random gulch
#

Hello so I have a couple children objects that I want to pivot around the parent but it seems like the pivot point changes depending on where each child object is and I was wondering if there a way for the pivot point to stay where the parent is at

leaden ice
#

You can toggle it by pressing Z

#

You have it set to Center right now

random gulch
#

Forgot to mention but I want to do this on runtime

leaden ice
#

Then you have nothing to worry about

#

Because the pivot of the parent doesn't change depending on its children

random gulch
#

Yeah I think that should be normally how it works but for some reason, my child objects pivot on themselves

maiden breach
random gulch
#

it's just rotating down

#

which is what meant to do

maiden breach
#

Whats the code youre using to rotate?

keen swift
#

I broke the fog on my built game, how do I fix it?

dim spindle
#

What's a good way to implement an inventory system? Basically, I need several features for my inventory:

  1. It has to be able to have the state of what items are held by different players synced between all clients, this means some field has to be serializable over the network (no managed types)
  2. It has to be able to save information about the item and how much of that item exists in an inventory slot, and there will be 3 slots dedicated to what the player can switch between holding.
  3. You have to be able to instantiate the object that is related to the specific item type for example when the player starts holding an items, you need to instantiate the prefab of the object to actually show that the item is being held.
  4. You need to be able to pick up an item and save information about it into the aforementioned inventory slots.

I was thinking about using Scriptable Objects, but I'm really not sure how to go about this. For example, how do I tie a specific type of my Item Scriptable Object (for example a lighter) so that when you pick up the physical object, it is saved into your inventory as being a lighter, instead of just an Item?

Or, how would you save the Scriptable Object data between throwing the item on the ground and picking it up?

And how do you tie a Scriptable Object instance to a Prefab you are instantiating?

Also I'm not sure, but I think network sync would be difficult without designing my inventory system around this idea a lot.

#

Does anyone know some good inventory system designs that can help solve these specific problems?

#

I can provide more information about my planned design the the inventory if anyone needs it, I'm just really not sure on the implementation and I don't wanna start working on stuff without a plan or without any ideas on what to use, and hopefully someone here with experience knows enough to give me some insight on how an inventory system that solves these problems would operate.

#

And please, avoid a solution that would be super tedious for adding new items or changing item properties

#

Sorry for my textwall of a question, just not sure how to get the question across.
TLDR: I want an inventory system with picking up and dropping items and storing data and with network sync; Actual details and info is in the textwall if you have experience with this.

limpid siren
#

Guys, Using Unity im trying to make a character jump and grab a rope, but i can't fix the Mixamo animation with the "rope" i created.
Can someone help me with the animation fix? first time doing the game in 3D

latent latch
# dim spindle What's a good way to implement an inventory system? Basically, I need several fe...
  1. Not much of an issue as most information will be client side, beyond what's visible to each other.
  2. IDs and scriptable objects
  3. The items should contain the information on what to display, otherwise it doesn't need to exist on the scene.
  4. That's the plan.

ScriptableObjects will make everything easier. They are just blueprints which you make along side your other item classes which you'll be reading from when you spawn items into your game. I suggest you figure out what type of items and their needed functionalities that you'll be adding to the game as that creates a lot more complexity when it comes to storing them in the right container, and using them from the right slot. An idea is to create multiple levels of abstraction, your base item derives into a useable item, which derives into an equippable item, and such. Ultimately, making what you want isn't super difficult, but I ran into trouble when I wanted to make mine into a traditional mmo inventory.

sour trench
#

@dim spindle I can't speak on the network part of this but it's actually really simple otherwise. Simply create 2 things; a BaseSlot class (or whatever you want to call it) and an ItemData ScriptableObject (or whatever you want to call it). These are base classes that you can derive from to create different behaviour. The ItemData class is immutable while the BaseSlot class holds the state of each inventory slot. It has a field for ItemData and another one for Amount, as well as getters/methods for working with the slot. Then in your PlayerInventory class or wherever you manage the inventory you'd just have a List<BaseSlot> slots field or List<BaseSlot<ItemData>> slots field if you decide to make BaseSlot generic, which can be a good idea because then you can re-use this class for other things like equipment as specify it as BaseSlot<EquipmentItemData> chest (where EquipmentItemData is derived from ItemData), recipes which require items and amount, among other situations. It could also be good to have a third class called Storage, which is what actually holds the slots field and all methods that modify the state of the slots. This way you can re-use the inventory logic for other things such as a bank or other types of storage, which is perfect for RPGs. Then in your PlayerInventory class you'd simply have a public Storage Storage { get; private set; } field. This is the setup I've gone for in my game and it works really well. I hope this helps.

tribal valley
#

Hi! I seem to have a problem I started making rogue-like game and want my character to be random. So I decided to instantiate a random player prefab but here is the problem. I'm using fsm for my combo attack and it worked perfectly fine when I drag and drop my player prefabs but when I random and instantiate it won't set the state back to main state for me.

normal kernel
#

i have an issue with netcode, my ServerRpc runs on the host but not on the client
how do i solve this
i can send code if you want
(and no, the forum post did not work for me)

ruby fulcrum
#

how do i fix my bullet going really off course? (green is the raycast representing the path its supposed to travel, yellow is the trial of the bullet representing its course, usually its fine but when i move far from the enemy and move around this occurs

code (in bullet script, under start)

//set position and rotation
        transform.position = bulletHole.transform.position;
        transform.LookAt(predictor.transform.position, transform.up);

        
        //create raycast to player predictor
        RaycastHit hitInfo;

        if (Physics.Raycast(bulletHole.transform.position
            , transform.forward
            , out hitInfo
            , 999
            , enemyAIScript.playerLayerMask))
        {
            //raycast hit
            //make bullet face raycast hitpoint
            Debug.Log("racycast hit");
            transform.rotation = Quaternion.LookRotation(hitInfo.point - transform.position, Vector3.up);
        }
        else
        {
            Debug.Log("no hit");
        }

        Debug.DrawRay(bulletHole.transform.position, transform.forward * 55, Color.green, enemyAIScript.enemyBulletDuration);

        //apply velocity to bullet
        rb.AddForce(transform.forward * enemyAIScript.enemyBulletSpeed, ForceMode.VelocityChange);
        hasShot = true;
wispy grail
#
    {
        if (Input.GetMouseButtonDown(0) && isAttacking == false)
        {
            isAttacking = true;
            animator.SetBool("isAttacking", true);
        }
       
    }

    private void onSwordSwingAnimationFinished()
    {
        animator.SetBool("isAttacking", false);
        isAttacking = false;
    }```
#

why is my attack get stuck when I press left mouse button quicky multiple time ?

#

onSwordSwingAnimationFinished() is linked to the animation event of the event basically when the animation finishes

hexed pecan
#

You setup your animator transitions so that its possible to miss the event entirely

#

Like when the event happens after or during an outgoing transition

main shuttle
deep willow
#

i need to write a pathfinding algorithm to find the nearest enemy while taking into account other objects. whats a good a way to do this?

thick plume
#

Is it possible to call file explorer during run time to make the user save a file as... ? if i try to look it up i only get basic crud operations

hexed pecan
cosmic rain
deep willow
#

i dont need to write it myself

deep willow
#

havent heard of NavMesh either

potent sleet
#

dont cross post next time bruh

hexed pecan
#

These are code channels, your problem is not code related, also dont cross post

hexed pecan
deep willow
#

for a 2d grid?

#

@hexed pecan

hexed pecan
fresh cosmos
#

i've been trying to get the correct canvas/screen position to move some ui to the cursor but its getting all wrong on different resolutions

Vector3 mousePos = Input.mousePosition;
Vector3 position = Camera.main.ScreenToViewportPoint(mousePos);
position.x *=  Screen.width;
position.y *= Screen.height;
position.x -=  Screen.width/2;
position.y -= Screen.height/2;
position.z = 0;

transform.localPosition = position;
transform.rotation = canvas.transform.rotation;

what should i do instead of this?

kind niche
#

Hello im back again with another error that google doesnt want to help me fix
So ive got a string that is pretty much just a console log plus commands that the player inputs and im trying to remove the last line.
Im using this:

text.Substring(0, text.LastIndexOf(Environment.NewLine))

but it always returns -1 even when debugging the text before returns new lines in the text
just confused about it

#

nevermind turns out using "\n" works instead

sterile echo
#

How does StopCoroutine works in this context?

#

Context (BattleManager) doesn't have Method overload for StartCoroutine and StopCoroutine

fresh cosmos
# fresh cosmos i've been trying to get the correct canvas/screen position to move some ui to th...

ok so im getting closer to something that seem to be working on any size but its extremely off, the position is like 10 times bigger than what it should be and idk why

Vector3 point = new Vector3();
Vector2 mousePos = new Vector2();

mousePos.x = Input.mousePosition.x * Camera.main.pixelWidth;
mousePos.y = Input.mousePosition.y * Camera.main.pixelHeight;

point = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, Camera.main.nearClipPlane));
        
transform.position = point;
transform.rotation = canvas.transform.rotation;
fresh cosmos
unreal temple
fresh cosmos
unreal temple
#

Changing the value

#

of these

#
    void Set(ref MaterialSlot slot, Material material) {
      using (ListPool<Material>.Get(out var materials)) {
        slot.Renderer.GetSharedMaterials(materials);
        materials[slot.MaterialIndex] = material;
        slot.Renderer.SetSharedMaterials(materials); // doesn't exist
      }
    }
fresh cosmos
#

from just reading the documentation it looks like the input list gets the output

unreal temple
#

Yes, that's the getter.

#

But I want the setter so I can update the values.

fresh cosmos
#

what i mean is this

// ...

slot.Renderer.GetSharedMaterials(materials);
materials[index].color = Color.white; // or whatever you want
// ...

thats at least what it looks like from the doc

unreal temple
#

I want to change which materials are there

#

That's disappointing lol

fresh cosmos
hexed pecan
unreal temple
#

And is now what I'm using.

#

I'll just optimize it when we upgrade to 2022

#

Not that important, I just wanted to avoid the garbage allocations

#
    void Set(ref MaterialSlot slot, Material material) {
      // NOTE: Unity 2022.2 introduces `SetSharedMaterials` for non-alloc
      // version of this.
      var materials = slot.Renderer.sharedMaterials;
      materials[slot.MaterialIndex] = material;
      slot.Renderer.sharedMaterials = materials;
    }
#

Just means I need to allocate an array for every material change.

#

Not ideal, but it only happens about 2500 times during mesh generation

#

So 2500*2 (for each slot)

#

5000*2 material references

#

So 80KB

#

not that bad :-)

#

But a lot worse than zero

fiery oracle
#

Hi! I am trying to get Unity tests working:

  • I placed the InventoryTests.cs script in the Editor folder to access the NUnit.Framework
  • However now the script is not able to recognize the scope of the Scripts folder

Assets\Editor\Tests 1\InventoryTest.cs(13,44): error CS0246: The type or namespace name 'ItemData' could not be found (are you missing a using directive or an assembly reference?)

using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;

[TestFixture]
public class InventoryTest
{
    [UnityTest]
    public IEnumerator AddItemToInventoryTest()
    {
        var itemGO = new GameObject();
        var itemData = itemGO.AddComponent<ItemData>();
        var sprite = Resources.Load<Sprite>("Healing Potion");
        itemData.SetInfo(1, "Healing Potion", "A healing potion", null, 1, 10, 5);
        var added = InventoryManager.instance.AddItem(itemGO);
        Assert.IsTrue(added);
        yield return null;
    }
unreal temple
#

I mean... you can nest your tests within the editor folder if you want.

#

So long as they have their own asmdef

#

Then you'll need to add a reference to your game's asmdef from the test assembly

fiery oracle
#

When I created the test script in a regular folder, NUnit.Framework was not found, and then a Google search mentioned that the script needs to be in the Editor folder to recognize the NUnit.Framework

unreal temple
#

So... in my experience you need to use asmdefs to get tests working

#

When you're using asmdefs there is no such thing as "an editor folder" and "a regular folder"

#

There are just assemblies which may or may not run on various platforms (including the editor)

fiery oracle
#

Ah okay, let me try that

#

By the way, this is what is confusing:

unreal temple
#

Do you have an asmdef for your main game code?

unreal temple
#

Either that or what you read was not true.

fiery oracle
unreal temple
#

It's possible this information is out of date

#

2015 was a long time ago

#

This is what my test assembly looks like

#

This is where it references my main assembly

fiery oracle
#

I have not done anything asmdef

unreal temple
#

Commit your work before doing anything here

#

This is how you might attempt to get it working...

  1. First create an asmdef in your Scripts folder. I call mine Game, a more conventional name might be Game.Runtime
  2. Create an asmdef in your editor folder, call it Game.Editor.asmdef
#

(all your code will break while doing this)

#

In Game.Editor you'll need to set it up to only work in editor, like so:

#

And you'll likely want to reference your main assembly here:

late lion
unreal temple
unreal temple
# fiery oracle I have not done anything asmdef

Okay, once you've done those steps, you may have lots of errors still. If so it's because your code can't automatically see all the assemblies in your project, and your dependencies (packages or asset store imports) may have their own asmdefs

#

You'll need to add them one-by-one to the correct assembly.

#

So... if something in your /Scripts folder has an error, look at where the type comes from and add it

#

Maybe ping me when you get to this part

#

But as an example, this is all the dependencies of my game assembly:

#

(they'll be different for you, and likely a lot shorter)

fiery oracle
#

Do you write tests for almost everything, or just critical stuff?

dim spindle
fiery oracle
#

Okay, I resolved most of the assemblies, with one last error:

#

One or more cyclic dependencies detected between assemblies: Assembly-CSharp-Editor-firstpass, Assembly-CSharp-Editor, Assembly-CSharp-firstpass, Assembly-CSharp, Assets/Scripts/Scripts.asmdef

dim spindle
# sour trench <@265112756322172929> I can't speak on the network part of this but it's actuall...

Yeah, this is more what I was looking for, but, I still am not sure on other details
Namely:
Storing information about what ItemData type should be added to inventory when you pick up a physical gameobject from the scene
I think if I have the item saved in the inventory, I can just have a field ItemData.prefab and insantiate that for the player to hold/throw
But that first point is still confusing to me

maiden breach
sour trench
# dim spindle Yeah, this is more what I was looking for, but, I still am not sure on other det...

Simply have one Item class with a public ItemData field. Then you always instantiate the same item prefab, and the item on the ground knows exactly what type of item it is. You would simply set the icon that you've defined in ItemData as the sprite of the SpriteRenderer of Item. No need to have different item prefabs in my opinion. I haven't found a use for it yet. For other things like actual objects in the scene it makes more sense.

fiery oracle
#

So I have an assembly for Scripts, and then the test assembly, which one should I add references to?

maiden breach
#

My guess is that you have dependencies going both ways between main assembly and scripts

dim spindle
maiden breach
#

Test should depend on the types it is testing. Nothing should depend on tests.

dim spindle
#

But that help a lot, thanks
Only one more thing- how would I set the type of an Item object that I manually place into the scene?
@sour trench

#

So I can make collectables

fiery oracle
#

So do I add all the assemblies to the Scripts assembly, and then just add the Script assembly to the Test assembly?

sour trench
dim spindle
sour trench
dim spindle
#

Would it just instantiate a new instance of the object when the scene loads?

#

Like the SO**

maiden breach
sour trench
#

@dim spindle The only instance you have to worry about here is the Item instance, if you make all your SO's immutable.

fiery oracle
#

Okay, so:

  • I was able to resolve most built in dependencies such as: TextMeshPro, Input System etc
  • The missing assembly definitions I was left with were custom scripts
  • Then when I dragged in the Script assembly to the Scripts assembly, that became the circular dependency
  • So how do I resolve the custom namespaces?
maiden breach
#

So dont reference all your assemblies in Test just for the sake of having them available. Asmdefs are for logically splitting up your codebase and reducing compilation time. Dont undermine that by tying it all together.

dim spindle
maiden breach
fiery oracle
#

Should I drag the script assembly into the test assembly?

sour trench
maiden breach
dim spindle
sour trench
#

@dim spindle Yes.

#

@dim spindle that's why you never want to have state in a SO, because you don't want to change the asset.

dim spindle
#

Ok I think I have an idea then of what I need
Thanks for explain this all to me lol

fiery oracle
#

I don't see which assemblies to use to resolve these:

#

I was assuming I could drag in the Scripts assembly I created based on the Scripts folder, however dragging the Scripts assembly into Scripts seems to have created the circular dependency

maiden breach
fiery oracle
#

So do I reference an already existing assembly, or have to create new individual ones for these?

dim spindle
#

So just
Item Script that stores any instance of ItemData so you can instantiate the 3d prefab if player holds or throws it and this item class stays on the object once its thrown
And then basic data structutre for the inventory
Sounds simple enough
Still not entirely sure on network impl but I think I can figure that out..
@sour trench is there some way to get a ref to a SO by a string? I think I could work with that

maiden breach
#

Delete Scripts asmdef @fiery oracle

fiery oracle
#

Okay, I was following this tutorial where they create the Scripts assembly: https://www.youtube.com/watch?v=PDYB32qAsLU

Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP

In this video I'll show you how to write more effective Unit Tests in Unity. More importantly, I'll demonstrate how valuable Unit Tests can be for Unity projects of any size and Unity developers of any skill level.

#Unity3D #UnityTutorial #GameDevelopment

📦 Download the co...

▶ Play video
sour trench
river wigeon
#

Is there an easy way to pass a float from one object to another through the editor? Currently I've made this...

dim spindle
maiden breach
river wigeon
#

That's what I was planning on doing but it seems kinda weird to have a class like the one I made

maiden breach
#

Yeah thats a weird class for sure

river wigeon
#

should I explain what I'm trying to do in more detail? There's probably a better way

maiden breach
#

Sure

river wigeon
#

so I have this class

#

I'm writing game logic using a state machine, and I want a condition which triggers after some time has passed

somber nacelle
maiden breach
#

Why is seconds its own class at all? Why not have it just be a float in the same class?

river wigeon
#

I want to pass in the value for how long that time should be

river wigeon
maiden breach
#

Serialize it in condition timer class?

somber nacelle
#

but why

river wigeon
#

well I want to pass in a float through the editor, so I could just serializefield on a float but I want the float to be the field of another class

hexed pecan
#

No need for the Float class as a middleman, just reference the classB from classA

maiden breach
#

Making your life harder for no reason

river wigeon
maiden breach
#

Thats not generic

hexed pecan
#

Probably means modular, not C# generics

river wigeon
#

modular yeah

maiden breach
#

Not modular either lol

#

Just adding a wrapper to float

river wigeon
#

well I store my timings in a GameLogic class

#

if I made it take a GameLogic object and then got the float from there then it wouldn't be modular at all

hexed pecan
#

I have used a class like FloatParameter that you can reference, and it has the value boxed inside it.
It's definitely not a MonoBehaviour class though

dusk apex
river wigeon
#

1 sec

maiden breach
#

ScriptableObject variables is what id use for this then

hexed pecan
#

How does SO help here?

river wigeon
#

So this is where I have the value stored

hexed pecan
#

@maiden breach I mean if he wants to directly reference a float

river wigeon
#

If I don't use a wrapper I have to do this

hexed pecan
#

Without referencing its owner object

river wigeon
#

which isn't modular as it has to take a GameLogic object

maiden breach
#

Theyre actually modular.

buoyant crane
river wigeon
mystic ferry
#

literally every video and blog about writing save systems in unity ALL use binary formatter

river wigeon
#

I have 3 different timings I need to store

mystic ferry
#

where can I find actually good advice that isn't for noobs about this?

hexed pecan
river wigeon
#

Serializing a float doesn't work either as I can't directly pass than through the editor, it has to be some kind of MonoBehavior

mystic ferry
#

I can cobble together a JSON system but I'm a little confused about how to apply encryption to it

river wigeon
#

It feels like there should be a better way

mystic ferry
#

I've seen stuff like nested using statements, not really sure

maiden breach
#

@hexed pecan SO vars live in the project as asset so they have no owner. You can save them as serialized references on prefabs

hexed pecan
#

@river wigeon Again, I see why you want to wrap a float into a reference type sometimes. But making it a MonoBehaviour isn't necessary at all

river wigeon
#

right

#

how do I pass it through the editor without it being a MonoBehavior?

hexed pecan
#

Not sure what you mean by "passing it through" the editor. You can store the reference to it in a field in any class

dusk apex
#

It's a value. It's copied or assigned newly. Inspector referencing and assignment is for setting defaults.

fiery oracle
#

So I deleted the scripts assembly and started fresh, now getting this error:

maiden breach
#

@river wigeon just make a Timings ScriptableObject. Create an asset out of it. Set your values. Drag it into a reference on your timer. Read it inside your timer class.

fiery oracle
#
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;

public class InventoryTests
{
    // A Test behaves as an ordinary method
    [Test]
    public void InventoryTestsSimplePasses()
    {
        // Use the Assert class to test conditions
    }

    // A UnityTest behaves like a coroutine in Play Mode. In Edit Mode you can use
    // `yield return null;` to skip a frame.
    [UnityTest]
    public IEnumerator InventoryTestsWithEnumeratorPasses()
    {
        // Use the Assert class to test conditions.
        // Use yield to skip a frame.
        yield return null;
    }

    [UnityTest]
    public IEnumerator AddItemToInventoryTest()
    {
        var itemGO = new GameObject();
        var itemData = itemGO.AddComponent<ItemData>();
        var sprite = Resources.Load<Sprite>("Healing Potion");
        itemData.SetInfo(1, "Healing Potion", "A healing potion", null, 1, 10, 5);
        var added = InventoryManager.instance.AddItem(itemGO);
        Assert.IsTrue(added);
        yield return null;
    }
}```
#

The test class is not recognizing the scope of the scripts folder

hexed pecan
maiden breach
hexed pecan
#

Just generally passing a value by reference

#

But you probably understood what he wants better

fiery oracle
#

Is the reason the test class not recognizing the scope because I do have to create an assembly for the InventoryManager and add that to the assembly references?

#

Or should I just create an assembly definition for the entire scripts folder?

dusk apex
#

Encapsulating a single data type in a wrapper seems unintuitive and would only make me assume you're creating an Editor tool for designers to sort of visually program through the editor (I've attempted this before) - one for non programmers. Usually you'd want objects to contain meaningful data and not simply wrap a single primitive (making everything into components isn't very ideal). If you're creating a visual "inspector" scripting tool, maybe consider Bolt #763499475641172029

maiden breach
summer nebula
high violet
#

I am trying to create a fight game like shadow fight
How can i start creating the versus computer
I mean how to code that?
Any video or links will help a lot

dusk apex
maiden breach
fiery oracle
#

These are the only two assemblies I have, EditMode and PlayMode, just generic

maiden breach
fiery oracle
#

one moment

ocean quail
# high violet I am trying to create a fight game like shadow fight How can i start creating t...

Don't take my word for it as I've been trying to release a game for 17 years and haven't yet, but I would start with getting a system down where you can 'play' the game assuming both/all characters are human controlled. Once you have that down, it's basically a process of replacing the logic for your 'human' or dummy characters handling inputs with an AI that pulls information from around the world its in and makes a decision to 'push a button' based on that.

brittle sparrow
#

Hello, I was wondering how I could perform operations on generic (primitive) types while containing the logic within my By() functions etc. Also Check() and Toggle() work only with bool, I limited the function to run only with booleans but it's a matter of accessing my List<T>'s elements as their data type rather than their generic type. Thank you very much for your time.

summer nebula
#

damn 17 years is a long time

#
  • cute kitty
lilac briar
#

Hey real quick, say I have a line inside a coroutine and I want that line to execute for the lifetime duration of the coroutine, as in executes once every frame that coroutine does it's thing, how do I go about that?

summer nebula
#

I mean if you stall the coroutine with waitforseconds etc then the entire coroutine would be paused

#

you could put it in a separate coroutine and keep reference to that coroutine in your first coroutine and then at the end just stop the coroutine

#

and have that line in an infinite loop in the second coroutine

#

I learned about them literally yesterday tho so don't take my word for it 😃

thick socket
lilac briar
#

The line assigns the color of an object to another object, I wanted it to execute every frame of the coroutine's duration, to keep both object's colors synced, if that helps illustrates what I'm trying to do better.

summer nebula
#

🤔

#

yeah if you pause the coroutine that has the line the only way in my mind would be to use a second coroutine

thick socket
#

^^

summer nebula
#

if that line depends on data that only exists within that coroutine tho that might get tough

thick socket
#

I would just start a 2nd coroutine and have that just run until a conditional you set in first coroutine ends

#

probably a better way to program it...but what I said would do what you want 😄

maiden breach
#

Sounds overly complex for just keeping two colors the same

thick socket
#

^^

lilac briar
thick socket
lilac briar
#

Yes

thick socket
#

whenever you set the 1st color just add another line to change 2nd also?

#

other thought is just use an event that the 2nd color subscribes to to change its color whenever the 1st color changes

lilac briar
thick socket
#

2nd has a return time for null so it runs every frame

thick socket
#

(I know nothing of SDKs lol)

thick socket
#

so you dont get a ton of them running at same time

lilac briar
#

Already made sure of that for the first coroutine.

proper pier
#

does anyone know how you can store player input over multiple (2-4) frames

thick socket
thick socket
#

frame 1, x=1, oldX=0, oldoldX=0
frame 2 x=2, oldX=1, oldoldX=0
frame3 x=3 oldX=2 oldoldX=1

#

etc

proper pier
#

so lets say x was GetKey.KeyCode.W

#

would that work for that or no?

thick socket
#

do you normally store it as a variable?

#

if it can be stored as a variable that works

proper pier
#

it can be stored as a bool

thick socket
#

now I might use a list to make retrieving/storing it easier...but same idea

maiden breach
#

if queue count > 4 dequeue, etc

proper pier
#

actually, now that I think about it, if I'm only processing movement once per how ever many frames, I just need to update a bool once if it is pressed durng that 2-4 frame period and it will always return the same result, so I think it sokay

thick socket
ocean quail
lilac briar
# thick socket then either should probably work

Doesn't seem to be working, the tweenning SDK function seems to be a coroutine in of itself, and the parent coroutine won't execute anything else until IT finishes executing.
Screw it, I'll just set it so that when the tweening function starts an event is called and the color syncing line is executed for a duration equal to that of the tweening function.
Thank you all for your help!

proper pier
#

can someone explain what the float that Input.GetAxis("Horizontal") or INput.GetAxis("Vertical") returns represents?

maiden breach
#

-1 horizontal is joystick all the way left, 1 is all the way right

proper pier
#

how about for the wasd keys?

hexed pecan
#

It works for WASD by default too

maiden breach
#

well then it would be digital instead of analog, so no gradient between

proper pier
#

digital?

#

I thought it was a gradient cause when I printed it it was still on a range from -1 to 1

hexed pecan
#

0 or 1 (or -1), but that's specifically when using GetAxisRaw.
GetAxis has some smoothing in it unless you turn it off in the axis settings

fiery oracle
proper pier
#

hm, so does that mean that the input you get from pressing D initallly isn't as strong as the input you get from holding input for 1 sec?

#

*output

fiery oracle
#

I had so little resources, I always dreamed about owning Click n Play

hexed pecan
proper pier
#

so if I switch it to getaxis raw, it should be constant, 0 or 1, correct?

hexed pecan
#

For keyboard input, yes

proper pier
#

okay, that's perfect for me, thanks for the help

hexed pecan
#

For joysticks, I think raw returns a gradient

#

Or well, the actual value of the joystick

proper pier
#

yeah, that would make sense. Since I need to consider player input over multiple frames, it's much easier if the input always returns a constant result no matter how long it is held

ocean quail
maiden breach
proper pier
#

I can definitely see some use cases where you would want to have gravity on tho,

ocean quail
#

I generally know how it works from test projects , just haven't gotten to implementing it yet. Very little input in what I'm designing so haven't thrown any resources at that yet.

slim spruce
#

there's no easy way to have a variable have one value whilst in the editor, and one value in the bulit version, right?

maiden breach
#

preprocessor directives @slim spruce

ocean quail
#

Where would that even be desirable? I guess you could fake movement smoothing based on that? I would expect for inputs to be ultra snappy if I was playing with with kb&m though.

slim spruce
latent latch
# dim spindle ... I already understand that part mostly lol I was looking for more specific im...

https://www.youtube.com/watch?v=bTPEMt1RG3s

If you want a better understanding of item implementation with the inventory, this guy has one of the better series on explaining this stuff in my opinion. However, gullefjun2's implementation of the inventory is similar to what I came about after rewriting mine a few times, and do highly recommend their way.

Tutorial series on how to make an inventory system in Unity, using C# and the Unity UI. In part 1 we build the base UI, implement Items using ScriptableObject and make the Inventory class. We'll also use the Character Stats asset (developed in another tutorial series).

► Next Video (Part 2): https://youtu.be/4JewzU_phTM
► Items & Inventory Play...

▶ Play video
thick socket
#

am I not able to setup IAP coding and such without already having a google developer account?

#

everything Im finding requires a developer account...which requires paying $25...which if I only want to pay once(as I plan to get LLC) means I need to make an LLC to avoid having to pay twice

#

(no clue if right spot or not since it kinda is, kinda isn't programming related)

valid raft
#

hi
why there is gaps between pieces ?

leaden ice
gray zephyr
#

Are there any good resources online for learning about the Factory Pattern and the Strategy Pattern in a Unity Game Development context?

#

I can't seem to find any Factory Pattern videos on YouTube alone

crystal holly
#

hey guys, i'm facing a weird issue here.. i am trying to set up communication between rhino/grasshopper and unity using tcp. i got it working so far and i am sending data back and forth but i am trying to rebuild my unity meshes each time after new data comes in. problem is that when i am creating a new mesh in unity my code just seems to stop running without any errors. the thing that trips me out is that it works completely fine when I run the CreateMeshes() method manually by pressing a key. could someone maybe point me in the right direction?

leaden ice
#

That will cause your background thread to unceremoniously die (hence the "seems to stop running without any errors" thing)

crystal holly
leaden ice
#

I'm going to guess you're running your code in some kind of callback function for the network request

#

That kind of thing will almost always run in a background thread

#

what you need to do is pass your mesh data into the main thread and create your UnityEngine objects (Mesh, GameObject, MeshFilter, etc) in the main thread with that data

crystal holly
#
    {
        set
        {
            _myMeshes = value;
            CreateMeshes();
        }
        get
        {
            return _myMeshes;
        }
    }```

So when I set myMeshes from the network callback I am getting problems with the CreateMeshes() function because this also runs in a background thread?
leaden ice
#

the network callback itself runs in a background thread

crystal holly
#

I see. How am I gonna get it to the main thread? 😄

leaden ice
#

Typical approaches are:

  • Use a ConcurrentQueue. Enqueue data from the background thread and poll the queue in a MonoBehaviour Update method with TryDequeue
  • Use a framework like UniTask to seamlessly jump around threads with stuff like ContinueWithMainThread or whatever it's called
kind tinsel
hot torrent
#

How do i call OnParticleCollision() but with a trigger? i want to have the same effect as with a Collider, but with a trigger on the target object instead.

crystal holly
hot torrent
#

or are they considered the same in this context?

leaden ice
#

triggers are colliders (with the is trigger box checked on)

hot torrent
#

upCario thanks!

#

i`ll see if i can get it working!

leaden ice
#

note that the trigger system for colliders doesn't work quite the same as the collision system. There are serious limitations. The main one being you have to explicitly list the colliders you want to interact in that list.

hot torrent
#

Yea, i just read...

#

So it's not very useful for my case!...

#

being a particle hitting a networked player.

acoustic scroll
#

I'm not exactly sure where to put this but I'm a programmer overseeing a build, so here goes:

Everything is working fine in the editor, but in the build all I'm seeing is UI elements over a black screen. It also looks like the loading canvas is hanging on the last frame of fading away, so I'm assuming the problem is that no cameras are rendering.

We're using URP in 2022.2.2f1. Anyone know what could cause this? I'm currently doing a fresh build on my own end to test some stuff.

#

The fresh build also seems to indicate that no cameras are rendering. Dark gray background, temp UI still visible even after it should be gone.

leaden ice
#

First thing to do would be to check the player logs and see if there are any errors

acoustic scroll
#

There are many errors from the FlatKit shader package and XR layout. They're being thrown in an alternating pattern.

#

Changing a couple more things to see what happens.

#

Side note, no code is being used on the title screen except when a button is pressed, so it has to be something renderer related.

wintry crescent
#

Hi, I have something like this

    [SerializeField]
    private IInput _defaultInputInterface;

where IInput is an interface
How can I make it possible to assign objects with scripts deriving from IInput in the inspector?

#

do I need to recreate IInput as an abstract class deriving from MonoBehaviour?

#

or is there a way I can keep it as an interface?

leaden ice
#

though i'm not sure even that will let you drag and drop

polar marten
wintry crescent
polar marten
wintry crescent
polar marten
#

it doesn't make sense, so avoid it if you can

#

even if you want to make a stub, the implementation will leak

#

it's not simple

wintry crescent
polar marten
#

use Input System if you want a good abstraction over inputs

wintry crescent
#

and just switch between them

slim adder
#

Hey guys, I have a question regarding colliders. My parent object has an interactable script, but it needs to have a collider for that. But the child has the mesh renderer. Is there a way to mimic the mesh collider from the child? So the parent has a duplicate of the collider of the child?

polar marten
wintry crescent
#

only 1 will be actually by the player

polar marten
# wintry crescent only 1 will be actually by the player

it doesn't make sense to have a separate IInput for these different scenes. the work you are trying to save - being "aware" of what "scene" you are in - cannot live inside the implementation of IInput, and if it does, it will leak in context from other places, so you will just be complicating things

wintry crescent
# polar marten that's not going to do what you think it does

I have a character with several different move functions
I am planning to have a reference in the character script, to the current script that controls the character
and I will call GetXInput() GetYInput() etc on that script
and it will change during the gameplay depending on different things

polar marten
#

it already has action maps, which you can enable and disable, including individual actions you can enable and disable

#

you can also change the input action referenced by public InputActionReference oneOffAction in a script

#

you don't want to recreate input system

#

carefully look at how it works

wintry crescent
polar marten
#

or the Player will need to be aware, not the implementations of IInput

#

don't organize your code this way and don't implement this, trust me

#

you want to learn Input System

#

and think about how to solve your problems using it

#

i don't really 100% know what your goal is

#

i have a 50% feeling

wintry crescent
#

I can't code custom movement into the input system, can I?

polar marten
#

or your colleagues didn't check in all the right assets

polar marten
#

what are you trying to do?

#

a first person narrative game with cutscenes?

acoustic scroll
polar marten
#

and what's your objective?

wintry crescent
# polar marten a first person narrative game with cutscenes?

It's more of a thing I'm trying out, it's not exactly a game
I want to be able to switch between different ways in which the character is controlled
so there would be this base class, and several deriving classes
One would be getting keyboard input and moving the character, like a typical third-person game
Second one would take control of the character and input several different moves in order, for example during a cutscene, then give control back to the first one
Third one would maybe control the character after clicking the destination on a map
all would work by calling roughly the same functions that would be called during gameplay, after pressing buttons on a keyboard

polar marten
#

Second one would take control of the character and input several different moves in order, for example during a cutscene, then give control back to the first one
this is generally not a good way to do this, because e.g. moving a CharacterController would not be deterministic enough due to varying fixed update calls

acoustic scroll
# polar marten how familiar are you with this project

I'm the lead programmer and built most of the project myself. The wild cards appear to be the shader packages our artists were relying on before we got a dedicated shader programmer.

I'm running some tests, reverting settings to default. There's some more renderer settings I need to change but I'm waiting on another build first.

wintry crescent
polar marten
acoustic scroll
#

We're using Plastic. It all works fine in the editor.

#

Actually looks quite nice.

polar marten
#

is this a built in render pipeline game?

#

and are they using amplify shader editor?

acoustic scroll
#

URP

#

I believe it is Amplify, yes.

polar marten
#

did they author their own full screen postprocessing effects?

acoustic scroll
#

Hm... I know there were some postprocessing effects included in these packages but I'm not sure if they're still in use. They certainly weren't in my test scene, but even that was still having trouble.

polar marten
#

is this an ordinary game, or one designed for a VR headset?

acoustic scroll
#

Ordinary

polar marten
#

@acoustic scroll right now your disease levels are medium.
key disease indicators:
✅ creating "custom shaders"
✅ using amplify shader editor
✅ artists directly modify the code base
✅ non-LTS version of Unity
✅ "it works in editor"
good results:
❌ artists are not using git
❌ you have a known working commit
❌ using URP, not using built in render pipeline
❌ ordinary, non VR game
❌ no custom postprocessing effects (that you know of)

#

it's really hard to say. the differential was pointing to render textures for post processing, until you reminded me it was URP

#

amplify shader editor is like the obesity crisis in the unity population

#

i'm sure you've tried running it in develop mode, and just inspecting the camera

#

the thing you need to hear and you are going to get mad at me about is that there is exactly absolutely zero reason anyone should be using ASE

#

the audience that uses ASE also messes with Z depth testing, which is basically something you also never need to do

#

you wind up with projects where the z depth testing settings are all created relative to each other, and do not make sense

#

and that's exactly the sort of "works in editor" situation i've seen

#

but not likely to be your problem

#

most likely there is just a script disabling your cameras. like it sounds like you've figured it out

#

(11) do you rely on script execution order for anything?

#

you can also create a camera in the scene, a new one

#

and see what happens when you build

#

see if it draws a picture.

#

could also be messed up exposure settings

#

but not likely in URP - much more common in HDRP

#

easy to repro in editor too

#

(12) hmm, or do you use #if UNITY_EDITOR in player scripts?

#

(13) and do you have any custom editor windows implemented?

#

if you answer yes to any one of these, your disease levels go up to high

#

if you answer yes to all three, your disease levels are very high

#

like people write braindead custom editors that do setup in the scene, and that can easily break your standalone build

#

like they just go and do side effects that aren't saved

#

especially if the custom editors or custom editor scripts set up things like lighting

#

same with UNITY_EDITOR being used for "debugging"

#

also a disease

#

script execution order can be different in player and editor, also a disease

#

do you see what i mean?

#

so the more you say yes to these, the more likely it can be anything

#

and if you merge code from "artists" that do these things, you know, because "it works in editor," the more likely only a bisect can solve this issue

acoustic scroll
#

I'll assume this "disease" or "infection" thing is intended as some kind of roleplay and not some kind of passive aggression.

I do rely a lot on script execution order for various things, but the test scene is completely fresh with nothing but a light, a cube, and a camera. The cube is using a default material, not modified at all. Nothing custom in the scene at all, and zero code.

Custom shaders are necessary for the game's art style; the practice can't be dismissed as incorrect, even if the tools in question may have quirks that need to be worked through.

polar marten
#

and even then, it's tedious, because you'll have to quit unity, wipe the Library/, and reopen unity, because especially custom editor code does so many side effects

#

that might not be checked in

polar marten
#

i think you should bisect unfortunately.

#

the best procedure is before every test, you should close unity and do the equivalent of git clean -dxf, which recreates the repo state as though it was freshly checked out

#

i know you're using plastic - which should really be one of the disease indicators - but i believe it has a similar piece of functionality

polar marten
#

they can add together to a catastrophe

#

i'm not saying you're doing anything wrong, but it is catastrophic if your simple test scene does not build

#

(14) do you use "scriptable object architecture"?
(15) do you use [RuntimeInitializeOnLoad]?

#

these are both things that can affect empty scenes in surprising ways

swift bison
#

Could any1 help me with my code? im a beginner and 1 thing wont work

polar marten
#

this includes 3rd party assets you may have imported!

swift bison
#

its pretty easy i guess

#

i get the error code The type or namespace name 'Scenemanagement' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?) [Assembly-CSharp]csharp(CS0234)

#

when i write : using UnityEngine.Scenemanagement;

polar marten
acoustic scroll
# polar marten > Custom shaders are necessary for the game's art style; the practice can't be d...

Your style of messaging certainly doesn't communicate this. Merely creating a new shader shouldn't be an indicator of "disease". It comes across as sarcastic and chiding.

I will say, I have been suspicious of the shader packages for some time. I'm always careful with how I structure my own code, and some of what it does is questionable. We've been planning to strip them out when we get the opportunity, but we have no time right now and our budget is paper-thin. Even still, it should be irrelevant given the context of a fresh scene.

I'll run more tests once this build is complete.

polar marten
#

the best thing to do is bisect

#

that is how i've solved issues in a similar situation - flaws in the built player with a subset of the disease indicators

#

in my case, i am sharing it was problems with Lighting and z testing

#

pitch black screen was postprocessing effects

#

you didn't answer yes or no to either of (14) or (15)

#

@acoustic scroll this is what debugging is though. so you can answer a plain yes or no and maybe that'll give me some more information

#

or not

acoustic scroll
#

I'd rather not waste my time.

polar marten
#

hmm i'm going to go with yes then?

acoustic scroll
#

I'll figure it out myself.

polar marten
#

hmm... well a bisect isn't that bad

#

i think you'll figure it out

#

"disease" is just a colorful exaggeration. many unity practices, even bad ones, lead to good games

#

@acoustic scroll but pretty much every single thing you say "yes" to of those questions can be a potential culprit for fully breaking your built player in a way that does not reproduce in editor

#

so you can go down the list and check the usage of every one of those features once you've bisected and identified the problem commit

#

maybe also you can read the logs in your development build and see

pearl swallow
#

Hi, so currently I am looking to make a shooting system where obviously the enemies shoot towards the player's position or at least around it. Currently this is how I have my update method set up (spawning the projectile but no force + other stuff that isn't important to it):

    void Update()
    {

        //Creates a tunneling system for the Plant based on time.
        plantTime += Time.deltaTime * plantInSeconds;

        if (plantStatus == 0 && plantTime >= 10)
        {
            PlantTunnel();
            plantTime = 0;
        }

        if (plantStatus == 1 && plantTime >= 5)
        {
            PlantUntunnel();
            plantTime = 0;
        }

        if (plantStatus == 2 && plantTime >= 2)
        {
            plantStatus = 0;
            plantTime = 0;
        }

        //Sets distance from player for shooting or biting.
        playerDistance = Vector3.Distance(player.position, transform.position);

        if(playerDistance <= plantRange)
        {
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));

            if (fireCountdown <= 0f)
            {
                Instantiate(poisonProj, poisonSpot.position, transform.rotation);

                fireCountdown = 10f / fireRate;
            }
            fireCountdown -= Time.deltaTime;

        }
        
    }
#

For the record the game is set to be in 3D not 2D, I've looked for aid on google and youtube for it but most just present 2D.

viscid kite
#

can overlap collider still work when the object with the collider is inactive?

leaden ice
pearl swallow
leaden ice
leaden ice
#

then the actual movement depends on how you want to move it

pearl swallow
#

That's it?

#

Really?

#

Huh.

leaden ice
pearl swallow
#

I don't know, half the time I use unity I'm expecting a complicated mess.

#

Thanks

tough storm
#

hey there, just wondering, profiling my game right now on-device and im getting 30fps. Most of the time per frame is rendering, but my game is all 2D, any idea what could cause this?

leaden ice
#

YOu need to profile the game running on the target hardware to see what the bottleneck is

tough storm
#

yeah i have it running on my phone and rendering is whats taking up the most time

#

WaitForLastPresent seems to be the issue

leaden ice
#

do you have a ton of objects

tough storm
#

nope, its just a bunch of Images

#

so if anything it should be taking up more memory than performance

leaden ice
#

define "a bunch"

tough storm
#

i couldn't tell you about the entire game, but for the starting room theres between 10~20 images

leaden ice
tough storm
#

and it runs at 30 fps

tough storm
#

after checking out the frame debugger and setting up a build to profile the gpu as well, im still confused

#

gpu is running fine, apparently the cpu is bottlenecking the rendering

#

yeah it was what you mentioned about the fps being locked

#

yoinked a little script to change the frame rate cap

dusky hare
#

Does anyone know how to localize the sprites from a "Sprite Swap Button"?

#

I'm using the localization package

#

I can localize the sprite of an Image Component with the "Localize Sprite Event" Component

dusky hare
clever lagoon
#

what do you mean by "localize" , usually that means language stuff.. but this is icons... do you want different icons for different languages?

#

@dusky hare

dusky hare
#

Yes, the Localization package allows for the localization of sprites

clever lagoon
#

ah.. so it looks like that script is giving you ONE sprite for each localization, but you want MULTIPLE sprites, one for highlighted, one for pressed, one for normal, etc... ?

dusky hare
#

Since a Sprite Swap button uses multiple sprites for each different state of the button, I'd like to localize all of those sprites

#

But the button object doesn't allow me to target them with the event

clever lagoon
#

can you show us what other options you see in the dropdown (currently showing image.sprite) ?@dusky hare

dusky hare
clever lagoon
#

Darn, I was hoping to access the member that has the sprites. Hmm, what if you create your own monobehavior, that has a separate function to change each icon. Can you reference those from there? @dusky hare

dusky hare
#

Ended up using the "Localize Prefab Event"

#

And created a prefab of the button, and prefab variants for the different locals

covert scaffold
#

I want to make a game like this. Static UI on the right and left boxes, and the upper-left will be a grid that you navigate through. Is it possible to place items in Unity relative to the screen itself?

#

Im honestly debating if something like Swing would be more suited for this task

leaden ice
versed marsh
#

how do i use the collab futere?

gray zephyr
#

Do you ever just get to the point where your commit messages just say "I have no idea what's going on"

cosmic rain
#

No..?🤨

#

You don't commit if you don't know what's going on.

clever sigil
#

I have no idea how but when i combine my meshes I end up with a bounds of 0

gray zephyr
cosmic rain
leaden ice
clever sigil
#

yeah the mesh is invisible
All I want to do is just combine meshes that use different materials in a way that the sub meshes that use the same material...are combined

cosmic rain
clever sigil
#

SO this is what it looks like before it attempts to be merged together

cosmic rain
#

How do you combine them?

gray zephyr
#

I find it very sad that I'm stuck using abstract classes to define contracts instead of interfaces simply because you can't have a field in the inspector to insert an interface instance 😔

clever sigil
#

well i have each of the tiles grouped into a chunk

#

and then i make a list of mesh filters that all use the same materials

#

and then attempt to combine those with merge submeshes on

leaden ice
clever sigil
#

and then try to combine those together with merge submesges off

gray zephyr
#

injection at runtime to complete the strategy pattern?

clever sigil
#

here's the function where I attempt that

#

and the part of the code that actually uses that method is a lot shorter

#
//merging
        foreach(Transform Child in this.transform){
            if(Child.GetComponentsInChildren<MeshFilter>().Length == 0) { continue; }
            Debug.Log("Running on " + Child.gameObject.name);
            Child.gameObject.AddComponent<MeshFilter>().sharedMesh = CombineMeshes(Child.GetComponentsInChildren<MeshRenderer>());
            Child.gameObject.AddComponent<MeshRenderer>();
            List<Transform> SubChildren = new List<Transform>();
            foreach (Transform SubChild in Child){
                SubChildren.Add(SubChild);
            }

            Transform[] SubChildrenA = SubChildren.ToArray();
            SubChildren.Clear();

            foreach (Transform SubChild in SubChildrenA){
                Destroy(SubChild.gameObject);
            }
        }```
leaden ice
# gray zephyr can I have a uh <:midshy:1048486297314009168> example?

Quick dirty example:

// The replacement for the interface.
public class Interactable : MonoBehaviour {
    public delegate void InteractHandler(Interactable source);
    public event InteractHandler OnInteract;

    public void Interact() {
      OnInteract?.Invoke(this);
    }
}

// The thing that would normally implement the interface
[RequireComponent(typeof(Interactable))]
public class Door : MonoBehaviour {
    void OnEnable() {
      GetComponent<Interactable>().OnInteract += WhenInteracted;
    }

    // don't forget to unsubscribe in OnDisable

    void WhenInteracted(Interactable source) {
      ToggleOpen(); // open/close the door when interacted
    }
}

// The thing that deals with the interface
public class CameraInteractor : MonoBehaviour {
    void Update() {
      // imagine some raycasting shit here
      if (raycastTarget.TryGetComponent(out Interactable interactable)) {
        interactable.Interact();
      }
    }
}```
#

Door and Interactable components both go on the door object

#

CameraInteractor goes on the camera / player or whatever
You can also freely make [SerializeField] Interactable x; variables and drag and drop them in inspectors.

clever sigil
#

I have no clue where the issue is

cosmic rain
cosmic rain
#

Also, you don't specify transformation matrices for the final combine.

#

That probably is the cause.

cosmic rain
#

And take a screenshot of it's preview.

clever sigil
cosmic rain
#

You cut out the preview window...

clever sigil
#

no it just was minimized

cosmic rain
#

Ok, so it is the mesh that is broken. The cause is probably what I said previously.

#

Try using identity matrix for the last combine.

clever sigil
#

that fixed it

#

though there's a new issue

#

when merging it seems to be getting rid of the submeshes

#

this is what it is supposed to be when not merged

#

And doing the math proves it, 84 * 256 (the tile amount of a chunk) is 21,504 triangles

#

when merged it only has 13,824

cosmic rain
clever sigil
#

ignore me doing math there, I dont know if that matters or not

#

I mean looking at the mesh data for the combined mesh we can see that it only has two submeshes

cosmic rain
clever sigil
#

which means when doing the first combine it's discarding everything but the first submesh in the individual tile meshes

cosmic rain
clever sigil
#

this is the initial mesh

cosmic rain
#

It has 3 sub meshes. Meaning 3 different materials.

clever sigil
#

that would be correct

cosmic rain
#

Yet you only check for the first material

if(m.sharedMaterials[0].name == GHAMaterials[0].name)
clever sigil
#

that's becuase the tiles themselves can only have 5 states; Grass A, Grass B, Rock, Water, Sand

#

wait

cosmic rain
#

Take a screenshot of your water tile inspector.

clever sigil
#

are you saying that each submesh would use a different mesh in that check?

#

where one tile object would get treated as 3 meshes?

#

that would make sense as to why onle the first submesh gets included

#

wait

#

eh I have no clue

clever sigil
cosmic rain
#

Take a screenshot of a tile object before it's combined.

#

Mesh renderer to be precise

#

Of a water tile

clever sigil
#

every tile uses the same mesh, the only difference between them is their transform and the materials they use

cosmic rain
#

How do you decide which material they use?

#

It has 3 mats assigned and water isn't even in the first slot

clever sigil
#

this function right here

cosmic rain
#

That still doesn't explain anything.

#

Why does it actually use the water material if there are 2 other materials assigned and all the meshes are the same

clever sigil
#

Well here are three tiles

cosmic rain
#

So you're saying that the other tiles simply don't have the water material assigned?

clever sigil
#

well they have it assinged to a unlit fully transparent material

cosmic rain
#

Ok, now I understand.

#

First of all, you combine the submeshes in the first combine. Meaning that the whole mesh would be using 1 material.

#

Second, you always only check the first slot of the material. And water material doesn't ever seen to be in the first slot.

#

That's why there are no water tiles in the combined mesh.

clever sigil
#

oh I see what you mean, yeah that second point makes sense

#

And how it works is that each tile has it's own unique first material slot

#

as in that the tiles have a unique first material name

#

so the name of the first material can be used to identify it

cosmic rain
#

What's WMaterials[0].name set to?

#

Ah, that's on the screenshot

clever sigil
#

that would be "Sand 1"

cosmic rain
clever sigil
#

Yeah I realized that and added it but it changed nothing

#

Identical results when combined

cosmic rain
#

Added where? The check is still never gonna identify it as Sand 1, because your tiles don't have it in the first slot. From what I've seen so far.

#

And you still merge the submeshes as I mentioned before:

temp.CombineMeshes(combine, true);
clever sigil
#

here's a water tile before merging

#

and here's what happens when I set merge submeshes to false

#

that's it

#

the only change

cosmic rain
#

I think, at this point you should break your algorithm down into several steps and execute each of them manually, inspectinging the intermediate results after each step.

clever sigil
#

I mean this is the entire file

cosmic rain
#

I'm talking about the mesh combining algorithm

gray zephyr
west lotus
#

Those are terrible commit messages 🤣

wide fiber
#

Script A

 private void OnCollisionEnter(Collision collision)
    {
        int player_hp = p_health.GetCurrentHealth();

        if (scriptOn)
        {
            if (collision.collider.gameObject.CompareTag("Player") || (collision.collider.gameObject.CompareTag("PlayerDash")))
            {
                player_hp--;
            }
        }
      
    }```

Script B
```cs
public class P_Health : MonoBehaviour
{
    private int currentHealth = 2;

    public int GetCurrentHealth()
    {
        return currentHealth;
    }

    private void Update()
    {
        healthTest();
    }

    void healthTest()
    {
        if (currentHealth <= 0)
        {
            Debug.Log("Game Over");
        }
    }
}```

Hi sorry. I'm trying to improve my coding here 😅  haha. So i tried this, but in script A when the object from script B collided with the wall, it didnt minus the hp. what wrong did i do here? 😦
simple edge
#

Int is a value type, not reference

gray zephyr
# west lotus Those are terrible commit messages 🤣

eh, it's a personal repository that I basically only have set up for practice on a project intended only for me to refactor the same 1 feature 12+ times to practice OOP principles and design patterns and understand them

I had literally never worked with C# as of a month ago, I'm learning from ground 0 :) so I don't care if these are professional at all

elder zenith
#

Hey, quick question, can you create local structs? As in, a struct for use only inside a function?

simple edge
elder zenith
#

Fair enough, touples just seem a bit bothersome to use sometimes

gray zephyr
simple edge
#

Yeah, otherwise you might want to use records, although I'm not sure unity has caught up to that point

#

Especially not struct records

elder zenith
#

Oh didn't even know those existed

#

Big thanks

wide fiber
#

or is that actually how we pass the health around? the legit way

simple edge
#

Well, value types are essentially just copied values
So if you say int player_hp = p_health.GetCurrentHealth()
You just get a copy of that value
Not a reference

#

So anything you do with player_hp doesn't actually modify the value it originally copied

#

To be fair
I don't know what GetCurrentHealth() does
But it probably should've just been a property instead of a full blown java style getter setter

This would've the advantage that you could've just written p_health.CurrentHealth--;

wide fiber
summer nebula
#

Yeah like mentioned above you should look at reference vs value types

#

And variable context, where you can access which variables from

#

And script communication

dim furnace
#

How do I fix the thing where the background trees are black

wild nebula
#

Anyone know how to NavMesh.Raycast only specific NavMesh surface?

#

I want to raycast but only for specific agent type's NavMesh

wild nebula
leaden ice
#

Not totally sure about that. I know that NavMeshAgent has a property for it

wild nebula
#

It seems like typeID isn't index, just found out.

#

Need to get from NavMesh.GetSettingsByIndex(int).agentTypeID

clever sigil
#

I figured it out, I had to further split every submesh when i wanted to merge it again

#

as it seems like when you combine a combined mesh it deletes everything but the first submesh

#

or something

#

whatever it is it works

uncut flume
#

Hello, i just joined here because i an doing a little game, i don't know a lot of coding and i have a couple of thing i want to do in my game but i have an error that i can't figure out, before asking for help I wanted to read all the read-me and community rules and i found out that you can paste code in the chat without it being a screenshot, there is a command on the #854851968446365696 that I can use to know how to do that but i want to ask if bot commands have its own channel or if its recommended to put it on some channel, or if i can input the command here.

uncut flume
#

!code

tawny elkBOT
#
Posting code

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

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

summer nebula
#

bot alert

thin aurora
#

<@&502884371011731486>

oblique spoke
#

!mute 1081604055920562176 3d Spam

tawny elkBOT
#

dynoSuccess NJFDSWAFXSD'PFDZS#1118 was muted

iron basalt
#

unrelated to unity, but does anyone know how to set a function as a parameter that will be assigned to a delegate? relevant example:

class asdjadhija {

delegate void Action();
Action _action;

public void SetAction(Func<string, string> action) {
this._action = action // does not work, problem is most likely in parameter for SetAction
}
}
#

im trying to have objects of this class have their own functions that are invoked by the same method (ex. member.InvokeAction() or whatever)

#

(also this is c# thats why i wrote it in here)

thin aurora
#

(maybe you want to hook to an event instead?)

iron basalt
#

oh so i shouldnt use a delegate in this case then

iron basalt
fleet furnace
# iron basalt unrelated to unity, but does anyone know how to set a function as a parameter th...

Maybe you want this?

class Assign {
    Action action;

    public void SetAction(Func<string, string> newAction)
    {
        action += () =>
        {
            string returnedString = newAction("input string");
        };
    }
}``` ACTION = some method that returns nothing (can take arguments via <>)
FUNC = method where the last parameter in <> specifies the return value. Everything else is a parameter.
So I am pretty confused by your use case here.
thin aurora
thin aurora
thin aurora
#

An event in c# is a simple hook and invoke when you call it

iron basalt
#

ya im googling it rn

fleet furnace
thin aurora
#

In this case, if you want custom behaviour to be invoked, maybe just use an event and pass a parameter to it

#

Only problem is that events will not be able to return a type, but you can hook multiple things to it

#

Hence my question, maybe you want an event instead, but if you want a return type that obviously won't work

iron basalt
#

the return value isnt necessary no

thin aurora
thin aurora
summer nebula
#

there's unity events and c# events

iron basalt
#

im just creating a MenuOption Class (some members are reused for different menus), when selected, they are Invoke() so to speak

thin aurora
#

I can see events being better for this

iron basalt
#

ya i could probably use an event

thin aurora
# summer nebula there's unity events and c# events

This is right. UnityEvents are better than events because Unity is able to properly serialize your event and display them in the inspector (I'm sure there is more to it, but this is the main thing I can think of).

#

other than that, I think they are the same thing

iron basalt
#

but i will still have to assign each member their own functions

summer nebula
#

I wouldn't necessarily call it better because of that

#

I hear c# events are more performant? but it shouldn't matter

#

it's just whether you wanna link things up in the inspector or by code 🤷‍♂️

fluid lily
#

Yeah, don't worry about performance over functionality. Performance can be achived easier then a working game.

summer nebula
#

events are pretty neat, good decoupling opportunities

swift dove
#

i have a problem

    private void Climbing()
    {
        if (Input.GetKey(climbKey) && ClimbAble)
        {  
            ClimbAble = false;
            rb.AddForce(0, climbDistance, 0, ForceMode.Force);
            
            Debug.Log("Climbed");
            
            state = MovementState.climbing;
            
            Invoke(nameof(readyToClimbNow), dashingCooldown);
            
            
        }```
climbable is a raycast to detect walls
how do i make it so when i press climbkey climbable remains false for a selected time
Hello?
#

because now when i climb it just shoots me to space if i hold

summer nebula
#

coroutines

swift dove
swift dove
summer nebula
#

idk try it out

fluid lily
swift dove
#

i dont even know how to make courinite

summer nebula
#

google it then

swift dove
thin aurora
summer nebula
#

coroutines

thin aurora
#

Verify your invoke actually works

swift dove
thin aurora
#

If Invoke doesn't work, use a Coroutine

swift dove
thin aurora
#

Not really

swift dove
#

9 minutes not a single message

main shuttle
#

You didn't even wait for 2 minutes

quartz folio
swift dove
#

bro its been 9 minutes

thin aurora
#

If this channel is active, so is that one. Have some patience.

quartz folio
#

It'll be a 90 minute mute if you don't just stick to one relevant channel

main shuttle
summer nebula
#

gotem

swift dove
#

ok?

#

bro its 1:20 pm for me

fluid lily
#

totally haven't had coding bugs that took months to fix

summer nebula
#

sooo true

swift dove
#

Thanks for the coroutine help

summer nebula
#

bro, some initiative to research things on your own is kinda part of the game

swift dove
#

yea ive been trying to fix this since 3 hours

summer nebula
#

🤷‍♂️

#

I been trying to finish this game for 2 months and I still look things up myself

swift dove
fluid lily
#

Honestly like I said, we don't have enough context to know. if your goal is to just have that not set to false for a while then coroutines ussually aren't used for that, but it could work in your case.

summer nebula
#

no one is gonna want to help you if you're demanding help and show no initiative

#

starter or not, if you rely on other people to think for you as a beginner you're never gonna learn

fluid lily
#

or be false for a while

swift dove
#

is ths enough

thin aurora
quartz folio
tawny elkBOT
#
Posting code

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

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

thin aurora
summer nebula
#

there's some really well explained coroutine videos on youtube

swift dove
#

okthanks

fluid lily
#

That is code, not context.

swift dove
#

but the problem is that in youtube the tutorials i see are using courinite(Trasnform)

#

im trying to cournite a litteral bool

quartz folio
quartz folio
#

and perhaps make a thread

thin aurora
narrow summit
#

How would I apply a tag/layer preset to TagManager.asset via Preset.ApplyTo()

iron basalt
thin aurora
#

Spoilers: c# is pretty performant and there are better things to improve on

summer nebula
#

I personally don't care much about performance, it was just something I heard 🤷‍♂️

#

but yeah, good point

wooden cove
#

I am having an issue with Unity AR that is causing objects to disappear randomly from the scene. Has anyone encountered something like this before and could point out a potential cause? there are no reported errors in the console, just an object that dissappears without any reason we can find

thin aurora
#

That said, events in c# are just very bland. I actually found out .NET has somewhat implemented the aformentioned RXJS features: https://github.com/dotnet/reactive
Apparently this is the equivelant to RXJS' observable: https://learn.microsoft.com/en-us/dotnet/api/system.iobservable-1?view=netcore-3.1

GitHub

The Reactive Extensions for .NET. Contribute to dotnet/reactive development by creating an account on GitHub.

fluid lily
thin aurora
#

If RxJS actually works in c#, it will be a million times better than events

summer nebula
#

cool stuff

#

I never used c# events so

fluid lily
wooden cove
fluid lily
fluid lily
summer nebula
#

I haven't even looked at delegates yet

wooden cove
fluid lily
wooden cove
summer nebula
#

Ahhh

#

I see

fluid lily
wooden cove
#

like, its still in the scene. but we can no longer observe it in the scene

#

it spawns, and dissapears from the scene at some point