#archived-code-general
1 messages · Page 51 of 1
I want it at whatever depth the 2d grid exists, probably that's why you suggest Plane.Raycast
Yep exactly
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.
When you dragged your textures into the palette the first time. Did you not create assets for the tiles?
Huh, they hide the info for some reason.
I suppose I can just unlock color in code
Yeah you can do that, or make a new tile type for it that lets you show it in inspector.
even with none tile it doesn't let you set Lock Color though
How do you like my save file? lmao
please I need help
the game works properly at first but when I load my game scene from the main menu, the player can't move anymore
check console for errors
why's everything red anyway?
Playmode tint
It's good practice that ensures you're aware that you're in play-mode - changes made to the scene may not persist!
ah cool, agreed, bit strong for my taste though
is it possible to enable momentum for the built-in character controller?
you can create momentum by smoothing/lerping the speed to its target value . . .
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
Kinda looks like you're making namespaces just for individual classes which seems excessive
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
It doesn't throw any error
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:
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
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.
TO me it looks like you defined it but never fill it in
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;
I have this already dont I?
you put that in defines, its not going to execute the find there
so it will remain null because nothign exists there
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
so where do I put it?
Here is how i would do it
Facade pattern my beloved
(Is the facade pattern acceptable in Unity development? Lmao) /gen
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
Thank you
AND in update it makes CERTAIN those have a value or it does nothing
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() ;
It needs to always be detecting the humanoids movement
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?
Yes
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
What exactly do you mean? I dont use patterns, so Can you explain to me please? Im all for learning
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 = ...
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!
error line 17 Humanoidblock still doesnt exist
im going to eat my computer
Dudes, do you know nav mesh generator for voxels? a tool for it, generate nav mesh for 3d voxels/grids
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
I have this word for word
unity is yelling at meee
:o
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
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
For the love of god use inteface and classes!
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.
Can events not be called from the animation events?
you mean Invoke event ? don't think so , Put the event in a method?
I did, but it doesn't seem to broadcast anything.
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.
which method are you talking about ?
I'm completely lost at this point, I tried several different things
post relavent code !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.
gimme a moment, I'll do that
ok I gotta run out real quick, but I'm sure someone here has a solution for you
thank you
a powerful website for storing and sharing text and code snippets. completely free and open source.
here's the relevant script
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.
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.
What's the method that's supposed to be invoked by the animation event?
Take a screenshot of your animation event setup.
StompImpact for some reason doesn't even come up, so I have to use StompLand()
@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.
making them public didn't work
I thought you would invoke the event whenever it's called and broadcasts the parameters
Animation events can only have no parameters or one parameter of a simple type like int afaik.
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?
I think your initial question is misleading. You said "can events not be called from animation events" which would imply that you're trying to invoke a C# event in a method invoked from animation event"
And it does. Does it not?
It is what I am attempting to do, but it is not invoking it.
Where are you invoking the C# event though..?
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);
}```
Invoking a method yeah. If that's what you want, then you're doing it already.
Yes, but it doesn't seem to be broadcasting anything
Or does one call it differently to broadcast?
You're not calling that anywhere
maybe I misunderstand how events work, I assumed invoking this would also broadcast the arguments
Strategy Pattern my beloved
No. You'd call EventManager.ExplosionInvoked(params) if you wanted the Event manager to invoke the event.@swift falcon
Oh I see, thank you! I'll try that
I see, it worked! Now to find out what stupid thing I did to overload my system lmao
@cosmic rain thank you
Try googling "Unity TLS allocator"
wdym "other normal"?
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 isdirection.normalized * speed
unless I'm missing something - maybe you could draw a picture?
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.
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?
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.
When you say "pick up the equipment" what lines of code are you referring to?
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.
this = ...
Cursed code
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?
static is a C# concept and the Assets folder is a Unity concept.
so you're kind of mixing metaphors here
and it's unclear what you want
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
that's called a ScriptableObject
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
drag and drop it into the prefab
not an issue
🤦♂️ I'm just dumb
[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();
}
Hello, question about Unity Localization:
How can I get get localized string from static class only using key?
Design patterns are hard 
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.
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
Change your tool handle position to pivot
You can toggle it by pressing Z
You have it set to Center right now
Forgot to mention but I want to do this on runtime
Then you have nothing to worry about
Because the pivot of the parent doesn't change depending on its children
Yeah I think that should be normally how it works but for some reason, my child objects pivot on themselves
Looks kind of like a non-uniform scale issue. Show scale of child objects?
nope that isn't an issue I am having
it's just rotating down
which is what meant to do
Whats the code youre using to rotate?
I broke the fog on my built game, how do I fix it?
What's a good way to implement an inventory system? Basically, I need several features for my inventory:
- 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)
- 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.
- 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.
- 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.
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
- Not much of an issue as most information will be client side, beyond what's visible to each other.
- IDs and scriptable objects
- The items should contain the information on what to display, otherwise it doesn't need to exist on the scene.
- 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.
@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.
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.
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)
Suggest you ask in #archived-networking instead
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;
{
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
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
Well you are rotating transform.rotation = Quaternion.LookRotation(hitInfo.point - transform.position, Vector3.up); and then using that new forward in your DrawRay, I don't know what you are expecting here?
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?
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
so what should i change
Do you need to write the algo yourself? If not, have you used Unity's NavMesh? It is decent
You'll need to use the platform specific API for that. If it's on windows, there's something in dot net I think.
i dont need to write it myself
hmmm i see
havent heard of NavMesh either
dont cross post next time bruh
These are code channels, your problem is not code related, also dont cross post
Plenty of tutorials for it out there
Not sure how it works for 2D. But this 3rd party package should: https://arongranberg.com/astar/
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?
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
How does StopCoroutine works in this context?
Context (BattleManager) doesn't have Method overload for StartCoroutine and StopCoroutine
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;
ok idk why all the examples i have come across say a solution similar to this. but what works for me is just input the raw mouse position without messing with it. which makes sense from what screenToWorldPoint actually does
How are you supposed to set the materials after calling this method?
https://docs.unity3d.com/ScriptReference/Renderer.GetSharedMaterials.html
what exactly do u mean by setting?
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
}
}
from just reading the documentation it looks like the input list gets the output
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
That is not what I'm looking for
I want to change which materials are there
Okay, looks like it has been added in 2022.2: https://docs.unity3d.com/2023.1/Documentation/ScriptReference/Renderer.SetSharedMaterials.html
That's disappointing lol

Am I missing something, why not just use the sharedMaterials property?
That accepts an array.
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
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;
}
Editor folder is not the right place for it, you should create a tests folder with the right asmdef. The test runner will do this for you the first time you open it.
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
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
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)
Do you have an asmdef for your main game code?
It's possible that if you remove the test assembly it will just work... I'm not sure. I was under the impression that you needed it.
Either that or what you read was not true.
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
I have not done anything asmdef
Well get ready for some pain
Commit your work before doing anything here
This is how you might attempt to get it working...
- First create an asmdef in your Scripts folder. I call mine
Game, a more conventional name might beGame.Runtime - 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:
Beware
https://issuetracker.unity3d.com/issues/removed-material-is-replaced-with-default-material-when-renderer-dot-setmaterials-is-used
Though your use case looks like it's just replacing a material, which should be fine.
How to reproduce: # Open the attached project "SetMaterialsBug.zip" # Enter Play Mode Expected results: No errors are thrown Actual ...
Thanks. It's working fine. :-)
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)
Do you write tests for almost everything, or just critical stuff?
...
I already understand that part mostly lol
I was looking for more specific implementation details
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
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
Cant have an assembly which is both a dependency and depends on another assembly. One or the other.
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.
So I have an assembly for Scripts, and then the test assembly, which one should I add references to?
My guess is that you have dependencies going both ways between main assembly and scripts
Im talking about physical objects in this context
Test should depend on the types it is testing. Nothing should depend on tests.
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
So do I add all the assemblies to the Scripts assembly, and then just add the Script assembly to the Test assembly?
Through the editor inspector of course, if you make the ItemData field public it'll show up there and you can pick what type of item it is.
Oh that does work? I didnt expect it to lol
Maybe I'm misunderstanding what you mean by manually..
Would it just instantiate a new instance of the object when the scene loads?
Like the SO**
It depends on your project, but in general I'd say no. You only need to add assemblies as references if youre actually referencing the code in the dependent assembly.
@dim spindle The only instance you have to worry about here is the Item instance, if you make all your SO's immutable.
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?
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.
How does a public ItemData field exist then?
I feel like im missing something..
Again, I cant see your project, but I'd check to see if there is a reference to another assembly in Scripts.asmdef that also references Scripts
Should I drag the script assembly into the test assembly?
I think you're mixing Item and ItemData up. Item is what you would place in the scene, and it simply has a reference to your SO instance via the public field. It doesn't create a new SO instance even if you have multiple Item game objects in your scene referencing the same SO.
Like I said before, only if youre referencing Scripts code in Test
Is the SO ref like an audioclip where it will reference a file in the assets but still be like
public AudioClip in the code?
@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.
Ok I think I have an idea then of what I need
Thanks for explain this all to me lol
Yeah
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
Do you need Scripts to be its own assembly? From the class names, they sound like they could just be main assembly kind of stuff.
So do I reference an already existing assembly, or have to create new individual ones for these?
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
Delete Scripts asmdef @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...
You can use the asset database to load it, although it's quite slow you if you can avoid it you should probably. You can load it using Resources.Load("Resources/path-to-your-asset"), the asset must be inside Assets/Resources folder for this to work.
Is there an easy way to pass a float from one object to another through the editor? Currently I've made this...
Ok, that makes sense
I forgot it was an asset so you can just throw it in resources
Get a reference to Float in the other script and call setVal
yeah
That's what I was planning on doing but it seems kinda weird to have a class like the one I made
Yeah thats a weird class for sure
should I explain what I'm trying to do in more detail? There's probably a better way
Sure
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
is vs code unconfigured or have you created your own type called Float
Why is seconds its own class at all? Why not have it just be a float in the same class?
I want to pass in the value for how long that time should be
own class
^
Serialize it in condition timer class?
but why
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
No need for the Float class as a middleman, just reference the classB from classA
Making your life harder for no reason
I want it to be more generic though
Thats not generic
Probably means modular, not C# generics
modular yeah
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
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
Why have primitives as components?
1 sec
ScriptableObject variables is what id use for this then
How does SO help here?
So this is where I have the value stored
@maiden breach I mean if he wants to directly reference a float
If I don't use a wrapper I have to do this
Without referencing its owner object
which isn't modular as it has to take a GameLogic object
Theyre actually modular.
make it take an interface instead
but what if I want to store multiple in the same class?
literally every video and blog about writing save systems in unity ALL use binary formatter
I have 3 different timings I need to store
where can I find actually good advice that isn't for noobs about this?
I've mostly seen JSON ones 🤔
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
I can cobble together a JSON system but I'm a little confused about how to apply encryption to it
It feels like there should be a better way
I've seen stuff like nested using statements, not really sure
@hexed pecan SO vars live in the project as asset so they have no owner. You can save them as serialized references on prefabs
@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
Not sure what you mean by "passing it through" the editor. You can store the reference to it in a field in any class
It's a value. It's copied or assigned newly. Inspector referencing and assignment is for setting defaults.
So I deleted the scripts assembly and started fresh, now getting this error:
@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.
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
Sure, but at that point the SO is the owner of that value.
Though if this is what he wants (shared immutable values between objects) then sure, SO is good
What do you think hes trying to do?
Just generally passing a value by reference
But you probably understood what he wants better
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?
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
Do you have more asmdefs you haven't mentioned? It's possible InventoryManager is getting picked up by another after you deleted Scripts and you're not referencing it in your Tests asmdef
I kind of did that with scriptable objects, creating wrappers for primitives could be a way to decouple your code
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
Creating unique instances of objects are fine. Making common primitives into components seems horrific though.
This is what people did before (or at least before widespread community knowledge of) scriptable objects. They'd use Monobehaviors on prefabs as data containers. Not a great pattern.
These are the only two assemblies I have, EditMode and PlayMode, just generic
Sounds like you're looking at TestRunner. You don't have any more asmdefs in your asset folder?
one moment
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.
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.
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?
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 😃
basically when you start the coroutine you want something to go for every frame?
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.
🤔
yeah if you pause the coroutine that has the line the only way in my mind would be to use a second coroutine
^^
if that line depends on data that only exists within that coroutine tho that might get tough
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 😄
Sounds overly complex for just keeping two colors the same
^^
The coroutine is doing other stuff, I want to avoid putting this line in the update loop because I only want it to execute while the coroutine is running.
feels like you only need to change the 2nd color when the first color changes no?
Yes
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
Don't wanna drown you in detail, but that's not possible, the first color is being changed by a tweening SDK.
How does the whole two coroutines approach work?
whenever you start the first coroutines just add a line below it to start the 2nd
2nd has a return time for null so it runs every frame
no way to subscribe to something that tells you when color changes?
(I know nothing of SDKs lol)
Below it not inside it?
long story short, you want to make sure each coroutine is only called once
so you dont get a ton of them running at same time
Already made sure of that for the first coroutine.
does anyone know how you can store player input over multiple (2-4) frames
then either should probably work
just store it in variable?
frame 1, x=1, oldX=0, oldoldX=0
frame 2 x=2, oldX=1, oldoldX=0
frame3 x=3 oldX=2 oldoldX=1
etc
do you normally store it as a variable?
if it can be stored as a variable that works
it can be stored as a bool
now I might use a list to make retrieving/storing it easier...but same idea
Queue would be ideal
if queue count > 4 dequeue, etc
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
figured that might be to complex for him but exactly 🙂
I love her so much she's the best.
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!
can someone explain what the float that Input.GetAxis("Horizontal") or INput.GetAxis("Vertical") returns represents?
-1 horizontal is joystick all the way left, 1 is all the way right
how about for the wasd keys?
It works for WASD by default too
well then it would be digital instead of analog, so no gradient between
digital?
I thought it was a gradient cause when I printed it it was still on a range from -1 to 1
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
Did you try Click N Play back in the day?
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
I had so little resources, I always dreamed about owning Click n Play
Yes, I believe that's the gravity setting on the axis. The axis properties are explained here:
https://docs.unity3d.com/Manual/class-InputManager.html
so if I switch it to getaxis raw, it should be constant, 0 or 1, correct?
For keyboard input, yes
okay, that's perfect for me, thanks for the help
For joysticks, I think raw returns a gradient
Or well, the actual value of the joystick
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
That's pretty wild, not that I've gotten to that point in my project or that it would matter for me but good to know.
Invest your learning points into InputSystem if you can
I can definitely see some use cases where you would want to have gravity on tho,
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.
there's no easy way to have a variable have one value whilst in the editor, and one value in the bulit version, right?
preprocessor directives @slim spruce
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.
oh sweet, exactly what i was looking for. TYSM!
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...
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)
Probably a question to ask Google developer support honestly.
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
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?
Sounds like you're accessing Unity Engine objects in a background thread
That will cause your background thread to unceremoniously die (hence the "seems to stop running without any errors" thing)
Yeah I was imagining something like that although I don't really know how the whole threading thing works..
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
{
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?
the network callback itself runs in a background thread
I see. How am I gonna get it to the main thread? 😄
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
ContinueWithMainThreador whatever it's called
Dose anyone know why im getting this error? or know what it means https://i.imgur.com/UXggM1W.png
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.
Understood. I'll have a look. Thank you!
Does this include triggers? I only see mentions of colliders
or are they considered the same in this context?
the entire page is literally about trigger colliders
triggers are colliders (with the is trigger box checked on)
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.
Yea, i just read...
So it's not very useful for my case!...
being a particle hitting a networked player.
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.
typical causes of differences in a build are:
- Code that depends on order of execution of scripts (perhaps your code that initializes the scene is not working properly due to this)
- Code that depends on specific framerate or resolution
- Platform-specific code
First thing to do would be to check the player logs and see if there are any errors
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.
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?
SerializeReference is required
though i'm not sure even that will let you drag and drop
don't do things this way. use
// IInput is now redundant
class BaseInput : MonoBehaviour /*, IInput*/ {
...
}
class SomethingInput : BaseInput {
public Something theThingThatWouldNormallyImplementIInput;
...
}
[SerializeField] private BaseInput _defaultInputInterface;
it does not
although it does appear in the inspector now
use the example I showed you
yep, that's the other option I meant, thanks, I'll do this
you don't need IInput at all. you will have one implementation*
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
I will have several input classes
One that will control the character during tutorial, one during gameplay, maybe some during cutscenes in the future
use Input System if you want a good abstraction over inputs
and just switch between them
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?
that's not going to do what you think it does
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
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
input system does this already
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
but the player doesn't control the character during those times
only 1 of those scripts will get info from the player, the rest will do arbitrary things on their own
input system can deal with this
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
no I mean the person who plays the game
only 1 of the scripts will take input from them
the others have other scripts that control the characters actions
I can't code custom movement into the input system, can I?
it sounds like you opened the wrong scene
or your colleagues didn't check in all the right assets
hmm well it'll be more helpful to maybe describe how to do this big picture
what are you trying to do?
a first person narrative game with cutscenes?
I'm looking this over myself, set up a fresh test scene and everything. The game is working correctly, except that no cameras are rendering.
how familiar are you with this project
and what's your objective?
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
this is exactly what input system and event system are designed for
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 aCharacterControllerwould not be deterministic enough due to varying fixed update calls
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.
it wouldn't have to do it blindly though
okay, and the artists are using git to check in their shaders*?
We're using Plastic. It all works fine in the editor.
Actually looks quite nice.
It all works fine in the editor.
oh no, you're infected
is this a built in render pipeline game?
and are they using amplify shader editor?
did they author their own full screen postprocessing effects?
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.
is this an ordinary game, or one designed for a VR headset?
Ordinary
@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
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.
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
I do rely a lot on script execution order for various things
then the level of problems are high right now
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
I'll assume this "disease" or "infection" thing is intended as some kind of roleplay
lol yes i'm just trying to illustrate that this is like, a bunch of little problems
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
Could any1 help me with my code? im a beginner and 1 thing wont work
this includes 3rd party assets you may have imported!
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;
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.
i am actually sharing my experience with a toon shaded project, i understand the challenges. the most robust approach uses Unity Shader Graph. i would look for an asset that implements toon materials using it
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.
anyway that's my opinion, i obviously want your game to succeed otherwise i wouldn't be trying to help you
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
I'd rather not waste my time.
hmm i'm going to go with yes then?
I'll figure it out myself.
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
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.
What's your question?
can overlap collider still work when the object with the collider is inactive?
The collider you are trying to overlap with must be enabled - therefore its GameObject must be active
How can I have an enemy shoot an object (lets just say bullet for simplicities sake) towards the player character's current position?
spawn it and point it in the direction of the player
ok got it
then the actual movement depends on how you want to move it
what are you expecting?
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?
Mobile operating systems will lock you at 30FPS if your game can't achieve 60fps or higher
YOu need to profile the game running on the target hardware to see what the bottleneck is
yeah i have it running on my phone and rendering is whats taking up the most time
WaitForLastPresent seems to be the issue
well what are you drawing exactly
do you have a ton of objects
nope, its just a bunch of Images
so if anything it should be taking up more memory than performance
define "a bunch"
i couldn't tell you about the entire game, but for the starting room theres between 10~20 images
Anyway you can use the frame debugger to see what takes a long time to render etc.
https://docs.unity3d.com/Manual/FrameDebugger.html
and it runs at 30 fps
Thanks, i'll check this out
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
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
However, it doesn't allow me to target any of the transition sprites in the button
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
Yes, the Localization package allows for the localization of sprites
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... ?
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
can you show us what other options you see in the dropdown (currently showing image.sprite) ?@dusky hare
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
Ended up using the "Localize Prefab Event"
And created a prefab of the button, and prefab variants for the different locals
Thanks for your help though
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
Yes. Two options.
-using a camera rendering to a Render Texture and drawn with a RawImage UI element
- modifying your camera's viewport
how do i use the collab futere?
Do you ever just get to the point where your commit messages just say "I have no idea what's going on"
I have no idea how but when i combine my meshes I end up with a bounds of 0
that was a depression post not a good practices post lmao
Does that actually affect anything in the game?
are all of your vertices (0,0,0)? 🤔
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
Bounds wouldn't make your mesh invisible, so probably what Praetor said.
How do you combine them?
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 😔
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
I find that it's often better in Unity to simply use a separate component without any inheritance/polymorphism constructs as an interface. The component can fire events which other scripts on the GameObject can listen to to "implement" the interface
and then try to combine those together with merge submesges off
injection at runtime to complete the strategy pattern?
can I have a uh

example?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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);
}
}```
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.
I have no clue where the issue is
Can you take a screenshot of the inspector of an object with combined mesh?
Here you go
Also, you don't specify transformation matrices for the final combine.
That probably is the cause.
Try double clicking the mesh field to select the mesh asset.
And take a screenshot of it's preview.
You cut out the preview window...
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.
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
There are 2 of the same material assigned in different slots.
Must be something with your logic.
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
It could be merging overlapping vertices. Not entirely sure though.
which means when doing the first combine it's discarding everything but the first submesh in the individual tile meshes
Do you have several submeahes on the initial meshes?
It has 3 sub meshes. Meaning 3 different materials.
that would be correct
Yet you only check for the first material
if(m.sharedMaterials[0].name == GHAMaterials[0].name)
that's becuase the tiles themselves can only have 5 states; Grass A, Grass B, Rock, Water, Sand
wait
Take a screenshot of your water tile inspector.
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
and what do you mean?
Take a screenshot of a tile object before it's combined.
Mesh renderer to be precise
Of a water tile
every tile uses the same mesh, the only difference between them is their transform and the materials they use
How do you decide which material they use?
It has 3 mats assigned and water isn't even in the first slot
this function right here
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
So you're saying that the other tiles simply don't have the water material assigned?
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.
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
that would be "Sand 1"
But on this screenshot you only just have Sand material
Yeah I realized that and added it but it changed nothing
Identical results when combined
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);
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
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.
I mean this is the entire file
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'm talking about the mesh combining algorithm
Update to my previous depression post
I have gotten to the point where my commit messages say "Shit WORKS" and that's much better
Those are terrible commit messages 🤣
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? 😦
Int is a value type, not reference
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
Hey, quick question, can you create local structs? As in, a struct for use only inside a function?
And I was making a joke 🤣
You can use a tuple
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples
But who is going to stop you from creating a struct
Fair enough, touples just seem a bit bothersome to use sometimes
ah,, my apologies
I'm really used to getting talked down to by elitists 
Yeah, otherwise you might want to use records, although I'm not sure unity has caught up to that point
Especially not struct records
am i trying too hard there?
or is that actually how we pass the health around? the legit way
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--;
yea you're right. this seems like im just torturing myself 😅
okok i follow your simple line! thank you
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
How do I fix the thing where the background trees are black
#archived-lighting not code
Anyone know how to NavMesh.Raycast only specific NavMesh surface?
I want to raycast but only for specific agent type's NavMesh
Thanks, I assume the typeID is index of the agent type?
Not totally sure about that. I know that NavMeshAgent has a property for it
It seems like typeID isn't index, just found out.
Need to get from NavMesh.GetSettingsByIndex(int).agentTypeID
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
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.
Nah just put them here
!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.
bot alert
<@&502884371011731486>
!mute 1081604055920562176 3d Spam
NJFDSWAFXSD'PFDZS#1118 was muted
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)
class asdjadhija
{
private Func<string, string> _action;
public void SetAction(Func<string, string> action)
{
this._action = action;
}
public string InvokeWhatever(string arg)
{
return this._action.Invoke(arg);
}
}
(maybe you want to hook to an event instead?)
oh so i shouldnt use a delegate in this case then
idk much about events in c# (unless they are similar to events in JS)
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.
Delegate is the base implementation but it's not the same as how object is the base of everything. I don't think you can lower any delegate-type method into an actual delegate
This is not how Action types work so this won't compile
Not sure about JS. I know RXJS subject, behaviour and all those types, but those are WAY better than c# will ever have
An event in c# is a simple hook and invoke when you call it
ya im googling it rn
Why would it not. Actions can be subscribed to. I am just constructing a lambda for that. Because his use case makes no sense.
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
the return value isnt necessary no
I can think of reasons why you would want to store a delegate in memory to be invoked later. It's a nice way of handling dependencies between files
Maybe more context is useful
there's unity events and c# events
im just creating a MenuOption Class (some members are reused for different menus), when selected, they are Invoke() so to speak
So you would need a MenuOptionSelected event
I can see events being better for this
ya i could probably use an event
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
but i will still have to assign each member their own functions
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 🤷♂️
Yeah, don't worry about performance over functionality. Performance can be achived easier then a working game.
events are pretty neat, good decoupling opportunities
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
Don't crosspost
coroutines
sorry
i coroutine the climable false? or the raycast
idk try it out
Not enough context to actually know. Also you don't normally coroutine raycast
i dont even know how to make courinite
google it then
well isnt there a way to make climbable = false last for a few seconds?
Then ClimbAble is not false as you think it is
coroutines
You should know how to debug these type of things
Verify your invoke actually works
And maybe stick to #💻┃code-beginner
climable is a raycast on the wall so when i hold V i dont want climable to just turn off for a split second
If Invoke doesn't work, use a Coroutine
its kinda ded
Not really
9 minutes not a single message
You didn't even wait for 2 minutes
This is not how discord works
bro its been 9 minutes
If this channel is active, so is that one. Have some patience.
It'll be a 90 minute mute if you don't just stick to one relevant channel
gotem
oh no 10 minutes
totally haven't had coding bugs that took months to fix
sooo true
Thanks for the coroutine help
bro, some initiative to research things on your own is kinda part of the game
yea ive been trying to fix this since 3 hours
🤷♂️
I been trying to finish this game for 2 months and I still look things up myself
cool good for you, mabye your not a starter
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.
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
or be false for a while
Maybe a tip: this is a pretty simple issue and Coroutines are not quite the black magic you could expect from Unity. Maybe looking into some tutorials on how Unity works would help you out?
👉 #💻┃code-beginner 👈 and post code properly using our guidelines !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.
The pinned posts in #💻┃code-beginner also has some nice links to get you started
there's some really well explained coroutine videos on youtube
okthanks
That is code, not context.
but the problem is that in youtube the tutorials i see are using courinite(Trasnform)
im trying to cournite a litteral bool
please take this to #💻┃code-beginner
ok
and perhaps make a thread
Each menu option you mean? That's the idea of a dependency-driven system. Something listens to your option being selected so it needs to hook onto it.
How would I apply a tag/layer preset to TagManager.asset via Preset.ApplyTo()
Each menu option you mean?
yes
I honestly would rather ignore any questions when it comes to how "performant" certain Unity/c# methods are rather than delving into it, unless it's very obvious like using any of the Findx methods. If you're unsure of performance, run a benchmark.
Spoilers: c# is pretty performant and there are better things to improve on
I personally don't care much about performance, it was just something I heard 🤷♂️
but yeah, good point
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
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
What type of object? Preset/scriptable/components?
If RxJS actually works in c#, it will be a million times better than events
Mhh there are alot of upcoming things, like multiple returns, that I am looking forward to, but unity is always years behind.
the object in question that dissapears is a prefab instance in the scene that was placed by the user
They are pretty basic. Just learning difference from Action/Event/Func/Delegate is a bit confusing.
Are you using a repository/versioning system in project?
I haven't even looked at delegates yet
I use this https://github.com/Cysharp/UniTask, to weigh in on the other convo
Just a way to make your own. Like Action/Event/Func are made from delegates.
yes, I do. everything is on github. project is quite big
Are the objects disapearing between the pulls/pushes, or while the project is open? I have had users not familiar with git make changes for them to a pull and revert everything they did in scene.
The object in question that dissapears is at runtime
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
thanks!