#archived-code-general
1 messages · Page 52 of 1
is it based on where you look
That sounds like some scripting thing, unless you are saying just visually disappearing. Try changing the shader on the object, other wise there are a few tools you can use to find all references to the object being used.
it might be, its hard to say what the exact cause is because we have very little info to go on
Have you checked the bounding box of your object?
If you're positioning it via shaders for example, then the bounding box isn't where the mesh is
you think the object might be considered outside the frustum?
so it'll disappear when you stop looking where the mesh is actually positioned
we are not using shaders to manipulate the geometry in any way
this can also happen with animated objects, sometimes you have to set them to not be culled or recalculate their bounds
the objects are also not animated
they are static meshes that are placed on an AR plane
each only has a few materials, with a default lit shader
No idea then, I can only imagine it's an AR-specific issue
culling could be an issue, why I was thinking if it is some custom shader on the object, though would seem like it would be consistent unless something is really going wronge with it.
it's very likely that it is, as it never happens in the editor no matter how much we move around and try to make it happen
Another aproach would be make a empty scene with that object and a camera. At this point you will probably just have to track down one thing at a time.
I figured as much. We are looking at the code to see if some event is firing without our knowledge.
Is there like a big game jam or something going on, begginer is exploding?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class dapipe_script : MonoBehaviour
{
public float movespeed=5;
public float deadzone = -30;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position += (Vector3.left * movespeed) * Time.deltaTime;
if (transfrom.position.x < deadzone)
{
Destroy(gameObject);
}
}
}
i need help with this
the if statement is not working
I don't know about any big jam going on. This is my actual work project
#💻┃code-beginner
Maybe try attaching a debugger and try fixing it on your own.
?
I hope your Visual Studio is setup properly. You can find more information there: #854851968446365696
Then you can ask in #💻┃code-beginner
If an artist has set a serialized color field to a color, and we want to convert that value to HDR, how can I do this?
I'm assuming that adding the ColorUsageAttribute will not reserialize the value.
(I'm assuming the data is interpreted differently for HDR, I don't know much abou this, just that the colors are rendering wrong)
Right, so HDR just extends beyond 1 for RBB?
Our issue is that when I set the colors in a VFX graph they're wrong.
So the lines of color overlayed (red+blue, yellow+red) are fromt he inspector
They're setting the colors in the bullets, which are much paler than in the inspector.
But when we set those colors in the VFX graph inspector they are true to the serialized value.
It could be a blending issue, post processing, or... a linear vs gamma problem
Maybe linear vs gamma
woudl be my guess
But they're just Color values right?
Or maybe the fields in the VFX graph are special in some way
It's all affected by that nonsense, and there has been issues in the past https://issuetracker.unity3d.com/issues/color-color-fields-except-gradients-in-the-vfx-graph-are-in-gamma-color-space
Repro steps: 1. Import the attached package, or in a new VFX graph set a color and a gradient block with the values (1, 0.23, 0). 2....
Hm. we're on version 13.1.8
But that does seem like the problem.
Okay, I'll try converting the value to linear space?
or... gamma space
lol I'm in over my head
I'll try both ways and see which works
That's what I try
Every time there's a colour issue I'm there with the conversions just to check
haha, yeah when we changed the project to linear space everything became pastel
So I'm guessing it's gamma being read as linear
Thanks @quartz folio ❤️
I keep having an error with a ?: operator
`public class Movement : MonoBehaviour
{
private Rigidbody2D rb;
public float moveSpeed;
public float rbacceleration = 7;
public float rbdecceleration = 7;
private bool facingRight = true;
public float velPower;
public int moveInput = 0;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.D))
{
moveInput = 1;
}
else if (Input.GetKey(KeyCode.A))
{
moveInput = -1;
}
if (Input.GetKeyUp(KeyCode.D))
{
moveInput = 0;
}
else if (Input.GetKeyUp(KeyCode.A))
{
moveInput = 0;
}
//calculate the direction we want to move in and our desired velocity
float targetSpeed = moveInput * moveSpeed;
//calculate difference between current velocity and desired velocity
float speedDif = targetSpeed - rb.velocity.x;
//Calculate if our moveInput is 0 it will de accelerate, anything higher than 00.1 will make us accelerate
float accelRate = (Mathf.Abs(targetSpeed) > 0,01f) ? rbacceleration : rbdecceleration;`
I get the error: Cannot implicitly convert type '(bool, float)' to 'bool'
but im not converting a bool to a float as far as i checked
rbacceleration & rbdecceleration both have a float value of 7
so accelrate should be 7 then
it's very confusing to me
Mathf.Abs(targetSpeed) > 0,01f
should be 0.01f
boom
Is there a collection like Dictionary but which allows to get values the other way around too?
collection[a] //returns b
collection[b] //returns a```
Something like this
No, if you need that you'll need to keep two dictionaries in sync
Although... there may be another solution
What is the type of the dictionary?
Yeah
I don't think there's an existing solution for that, but you could implement it yourself.🤷♂️
Then just enter everything twice.
That could work👆
Potenitally you could do this too
HashSet<(MyType, MyType)> _set;
But that's only if you want to check if the connection exists
If you want to actually retrieve the other value just enter everything twice.
So like:
void LinkTheseThings(Foo a, Foo b) {
collection[a] = b;
collection[b] = a;
}
void RemoveThisThing(Foo a) {
if (collection.TryGetValue(a, out var b)) {
collection.Remove(b);
}
collection.Remove(a);
}
HashSet will do, thank you
what.. is a hashset
The problem is you need some way of sorting them
It's easy with integers etc
But the hashset needs to have the keys in a predictable order
For example:
bool LinkExists(int a, int b) {
(int, int) key = Sort(a, b);
return _hashSet.Contains(key);
}
It's a bit harder with references
Then will have to think about something else
Ah cool, so these are the eges?
And I'm trying to create the trails properly
Hey don't shit on telov
So I thought of starting with a random node and then going all over its connections creating trails
Meanwhile storing the created pairs so that I do not create duplicates
That's what I'm trying to do
Just create a Node class with a list of Nodes
Yeah, I'd probably do that too.
Easiest for recursion
class Node {
List<Node> _edges;
}
I have this for now
public class Node : MonoBehaviour
{
[SerializeField] public List<Node> connections;
private void OnValidate()
{
foreach (var node in connections)
{
if (!node.connections.Contains(this))
{
node.connections.Add(this);
}
}
}
}```
well then you don't need a dictionary
You can just do:
if (node.Connections.Contains(otherNode)) {
But they both have each other
So what?
yeah, that's right.
A graph is like a doubly linked list
If A -> B but B is not connected to A then it means you can move from a to B, but not from B to A
In this example everything is doubly linked
Alternatively you can give each node an ID and then use the HashSet example from above
I would consider that option
Just make sure that all the nodes are created with a unique ID
If you have an array of nodes it can be their index
But there's nothing wrong with this:
static void Link(Node a, Node b) {
if (!a._connections.Contains(b)) a._connections.Add(b);
if (!b._connections.Contains(a)) b._connections.Add(a);
}
I'll just create a recursion I guess
Hello guys Iam making a vr project for school and iam trying to make objects have an outline when you touch them but I can't find anything on it online is there anyone here that could help me?
search for outline shader
I have and everything I'm finding on it is either for mouse and keyboard not vr or has the object highlight always not only on hover enter
Ask in #archived-shaders
This article mentions that you shouldn't use occlusion culling for outdoors, is that correct? https://thegamedev.guru/unity-performance/occlusion-culling-tutorial/?utm_source=youtube&utm_medium=video&utm_campaign=occlusion_culling
Depends on the outdoors, but generally, yes
What do they mean by "(occlusion areas) These areas are typically where the camera can go through."
each node should have two ports, e.g: output and input, this way it would be very easy to sort things out
and those ports can accept multiple inputs/outputs from multiple nodes. Similar to GraphView api
More specifically, how do you decide where to set the occlusion area?
You need to bake the occlusion data.
I mean manually setting the box area. How do you decide the bounds of each occlussion area box?
An occlusion area is an area of interest where we want to bake occlusion culling at a higher precision:
Areas closest to the player
unity docs do a better job at explaining
I want GridPos2D to be like the Vector2, just with integers. How can I make x and y show in the inspector?
you know Vector2Int exists already, right?
Ummmm, no?
You are a literal life saver. For years I had no idea 🙃
Well now you do!
Also in regards to the issue you presented, as long as you have a serialized field of type GridPos2D it will show in the inspector
Great. Thank you
Hello,
I used the localization package
But when I have a "\n" in my localized string, we see these on the screens.
How can I add newline in my localization ?
Thx in advance
when switching from level two to level three, an animator controller for the transition fade, deletes from the inspector. it works fine from level 1 to 2.
it turns it into a toggle button where the float will be 1 or 0 depending on the toggle state
Anyone use git source control and how do you manage large binary files (LFS support)?
is it fine 'out of the box'?
Hey is there a best practice for handling the communication between multiple Managers?
One manager to rule them all🤔
Question:
Given this piece of code:
RaycastHit hit;
trackDetected = Physics.SphereCast(transform.position, sphereRadius, transform.TransformDirection(-Vector3.up), out hit, rayDistance, layerMask);
Vector3 normal = hit.normal;
Is hit.normal in world space or in local space?
it is always the world space normal
yes
because it's a property
colorOverLifetime is a property and it's a struct
so you'd only be modifying a copy
strangely enough, the way Unity implemented the particle system modules this wouldn't actually be an issue - but C# doesn't allow it to prevent potential bugs
gotcha
the piece I don't follow is how setting it to a variable then setting color works
yet making it all in 1 line doesnt
because C# doesn't want to let you do it if you don't have the ColorOverLifetimeMpodule saved in a variable
because it doesn't want you to lose the changes
gotcha thanks
but again, since Unity implemented these structs in a weird way, it wouldn't actually be an issue like it normally would
Considering it's a struct, hence value type, the first two lines won't work either
for example for a Vector3 this would be an issue
They will actually.
its what the unity doc says to do
¯_(ツ)_/¯
Unity implemented the structs this way
Unity changed the way structs work?
color is a property that actually sets the native data properly
Lol this engine
They made it so complicated
yes
they should have just done it normally, but Unity is Unity 😆
I think they thought they were simplifying it
What would have been the normal way?
requiring you to write the struct back to the particle system
item.colorOverLifetime = col; (after making your changes)
that would have made more sense in my mind lol
NullReferenceException: Do not create your own module instances, get them from a ParticleSystem instance
void SetParticleColors(bool isDefault)
{
Gradient grad = new();
RarityColors rColors = new();
//item
if (isDefault)
{
grad.SetKeys(
new GradientColorKey[] { new GradientColorKey(Color.white, 0.0f), new GradientColorKey(new Color(0.00392f, 0.20784f, 0.30980f), 0.6f) },
new GradientAlphaKey[] { new GradientAlphaKey(0.0f, 0.0f), new GradientAlphaKey(0.6f, 0.13f),
new GradientAlphaKey(0.6f, 0.83f), new GradientAlphaKey(0.0f, 1.0f) });
}
foreach (var item in allParticles)
{
var col = item.colorOverLifetime;
col.color = grad;
}
}```
its getting mad at me for the col.color = grad;
Im not sure why...I followed the unity documentation for it
what is allParticles?
allParticles = new List<ParticleSystem> { particles, particlec1, particlec2, particlec3, particlec4 };
ah dang, looks like I missed serializing one in editor
Oops, that would be because Unity's fake null object in the editor. Instead of assigning null, Unity will assign an object that is supposed to throw a "MissingReferenceException" if any of its properties or methods are accessed, but I guess they forgot to do that for ParticleSystem modules.
Hi im new here so I dont know if this is the right channel to ask how to code specific thing but here goes.
So I made a List/Array. And I want to Instantiate those game objects and I did it. It worked BUT I want it to instantiate limitly for example
Gameobject A, B, C, D
so I want to instantiate gameobject A and B from the array/list without game obeject C and D being instantiated.
Hello idk if this is to place to ask, but idk what to do, i have a script called item, whenever a gameobject with this script becames a child its stops updating, the script remains enabled but it stops updating(the gameobject is active too), what is this? how can i fix it?
So only instantiate the first two.
As long as it's enabled and active, it will continue to update. Did you make a child of a deactivated object perhaps?
yes. cause Im making like random spawner. I just want it to spawn 3 things out of the array/list
Use a for loop with a limit of 3
nooo i checked, its still active when it becomes a child
for (int i = 0; i < 3; i++) {
...
}```
then it will update
Share details if you're still confused
prove it
will try that
It works thank you. I dont know why I didn't think of it
i have this script as you see there is a print that should be alway print "!" but when i make the object a child it stops
and you can see it here that its enabled
and nothing happens it just stops updating
show what you made it a dchild of
show the hierarchy when it stops
etc
also you really should not be doing FindObjectOfType in Update - let alone multiple times. But that's a separate discussion
and show the inspector for Crucifix, as well as the console window
i know its just some test code i was tryna do to solve this bug
it stopeed after 4
because thats when i picked it up
The script in question is Item?
yes
Based on what you showed - it shouldn't stop updating. What happens if you restart Unity?
let me try it, but in my understanding that shouldnt change anything cuz unity compiles the game every time i hit play and that should fix an error like this
Nothing should stop Update as long as the GameObject is active and the component is enabled
it stops after restart too 🥲
i know thats why i asked you guys here on dc
i work in unity for a good time now and i never see something like this
Nor have I 🤔
and the funnier that this is an lts version of unity so it should popped up before
and the even funnier bit that when i unchild the item object it continues updating
silly question but can I see the pickup or waepon slot code or whatever
maybe it's deactivating and reactivating the item every frame or something
that could interrupt Update
how do you handle activating and deactivating the hands_n objects?
this code runs when something happens that sould change the hand sprite, then it stores the current index of that sprite in the "righthand" variable
there we go
exactly what I was thinking
you're deactivating them all in that loop
for (int i = 0; i < Hands.GetChild(0).childCount; i++) {
Hands.GetChild(0).GetChild(i).gameObject.SetActive(i == r);
Hands.GetChild(1).GetChild(i).gameObject.SetActive(i == l);
}```
Try replacing the loop and the two lines after it with this ^
Right now you're deactivating then reactivating each frame probably. So it appears always active in the inspector/hierarchy, but you're not letting Update run.
i fooouuund the problem thanks to your idea of something disrupting the update, it was an else if, that should be just an if
thank you very much!
does anyone know if a quick way exists to make the values of 1 script match another of do I need to 1 by 1 copy them over?
2 difference instances of the same script
copy/paste values in inspector
if (plantIndex == 0)
{
transform.position = new Vector3 (tunnelArray[0].transform.position.x, tunnelArray[0].transform.position.y-10, tunnelArray[0].transform.position.z);
}
So I'm trying to have a GameObject move down in y value by a certain value. I've tried other versions of it, to no success. I've had done it before, but now I'm not sure why it is no longer working.
Wait-
simple way is to serialize/deserialize, not that I would recommend this, you could also use Reflection
Would I just subtract it by not including the tunnel array part?
If you aren't updating tunnelArray, whatever that is, then yeah, you're just setting it to the same value-10 over and over again
The array has a certain number of empty GameObjects that do not change actively, it's a list of transform values.
Is each element supposed to represent an offset?
It is supposed to represent a new position that the GameObject moves to when the PlantIndex, which is a random), adjusts accordingly.
It's just in a certain instance of the code, it is supposed to move down by 10 until I can get an animation done for the object.
It's meant to be a placeholder code to represent what the animation is supposed to do.
It moves to the positions just fine.
I just can't subtract the Y value.
From the y value*
There's nothing wrong with that code, assuming index is 0 it should be set to Tunnel0-10. I would make sure 100% that that code is running, and furthermore that something else isn't resetting the position back to something else.
transform.position = tunnelArray[0].transform.position;
This is in the start method but that shouldn't do anything but set up the initial.
Another section has it move back into the regular position (no subtraction to Y), but that wouldn't be called unless the other if statement in the update method had the parameters set.
you need to show the (full) code and explain the desired behavior. Right now we just have little bits and pieces and not the whole picture of what you're doing
public void PlantTunnel()
{
plantIndex = Random.Range(0, 3);
plantStatus = 1;
if (plantIndex == 0)
{
transform.position = new Vector3 (tunnelArray[0].transform.position.x, tunnelArray[0].transform.position.y-10, tunnelArray[0].transform.position.z);
}
else if(plantIndex == 1)
{
transform.position = new Vector3(tunnelArray[1].transform.position.x, tunnelArray[1].transform.position.y - 10, tunnelArray[1].transform.position.z);
}
else if (plantIndex == 2)
{
transform.position = new Vector3(tunnelArray[2].transform.position.x, tunnelArray[2].transform.position.y - 10, tunnelArray[2].transform.position.z);
}
else
{
transform.position = new Vector3(tunnelArray[3].transform.position.x, tunnelArray[3].transform.position.y - 10, tunnelArray[3].transform.position.z); ;
}
}
why would you write it this way 😱
transform.position = new Vector3 (tunnelArray[plantIndex].transform.position.x, tunnelArray[plantIndex].transform.position.y-10, tunnelArray[plantIndex].transform.position.z);```
this replaces ALL of those if/else blocks
also Random.Range is exclusive, so it will never choose the final array element
I was following stuff from google and etc.
I try to use that before going to here.
Which I should stop doing since this is a valuable resource.
arrays exist to avoid this exact kind of repeated code, for future reference
If you ever find yourself explicitly writing a number in like someArray[1] you should stop and think - you're probably doing something wrong
it should almost always be a variable
likewise if you're repeating the same code for different indices
I don't really mess around with arrays too often, so I'm not knowledgable in them.
Also a somewhat less verbose (and more performant) way to do this:
transform.position = tunnelArray[plantIndex].position + new Vector3(0, -10, 0);```
Thanks
public void PlantUntunnel()
{
transform.position = tunnelArray[plantIndex].transform.position;
}
So for this method, it should just move it to the original position of whatever tunnel has been selected?
I adjusted it to match what you gave me.
assuming the position of whatever is in the tunnelArray isn't changing, then that sounds correct
Well, it didn't...
Lemme copy the rest.
void Start()
{
transform.position = tunnelArray[0].transform.position;
plantStatus = 0;
navMeshAgent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
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 && plantStatus == 0)
{
transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
if (fireCountdown <= 0f)
{
GameObject poison = Instantiate(poisonProj, poisonSpot.position, transform.rotation);
poison.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward*500);
fireCountdown = 10f / fireRate;
}
fireCountdown -= Time.deltaTime;
}
}
This is the rest minus anything above start.
where are you changing plantStatus now?
Use a paste site and share the whole script 🙏
when preator said that his code replaced all the if statements, I think you accidentally removed that as well
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
When I transition to another camera, there is a little delay where do I remove that? Timeline with cinemachine!
Second index was removed because it was causing conflicts, basically my attempt to do a non-repeating random (which I quickly realized does nothing.)
It should work, I don't see anything that is overriding it... unless I need parenthesis-
Hold on.
No, okay, didn't do anything.
I’ll keep looking around in a bit, I gotta eat.
How do I get all objects which lay in the game on top of the object?
I am trying to use Physics.Boxcast but it doesn't work
Is boxcast the right thing to use in Unity3d?
Or how should I do it?
This code is not working
i am using the new input system
and clicking on the gun doesnt have any effect
do you have an event system in the scene?
Any errors in console?
there is one, but it doesnt seem to be responding to other unity events either
is there a way to regenerate the eventsystem?
Use boxcastAll to get an array of colliders https://docs.unity3d.com/ScriptReference/Physics.BoxCastAll.html
does your canvas have a Graphic Raycaster?
And lastly - do you have any other canvases in the scene?
Okay great thank you!
public event Action<Items> addItem;
public void AddItem(ItemReqs itemReq)
{
//addItem?.Invoke();
Items item = new(itemReq);
addItem?.Invoke(item);
List<Items> tmpList = FindList(item);
tmpList.Add(item);
}
public void AddItem(Items item)
{
addItem?.Invoke(item);
List<Items> tmpList = FindList(item);
tmpList.Add(item);
}
first try using events...thought I had this setup right from the example Im following so not sure what is wrong
you need an object reference for the PlayerInventory instance you want
you can't just use the class name
awesome thanks!
i have like 6 other canvases in the scene, and yes it does have a graphic raycaster. these are are all canavases
I would also recommend renaming your event to something like OnItemAdded which is more descriptive of what the event is.
gotcha thanks...thought you were able to do it without needing reference to PlayerInventory?
the way you have it now seems confusing because it seems like it is actually adding the item rather than a reaction to adding the item
You always need object references to access non-static members of a class
(following some tutorial that had things with collectable class that other subscribed to)
the event is a non-static member, so you need an object reference
If you use a static event you don't need an object reference.
of course that has other pitfalls 😉
"me about to just make it static"
is it bad that i have different canvases for different things?
no
so what could be causing my issue then? im slightly confused
Your other canvases may have things that are blocking this one
For example a fullscreen image on one of the canvases that's in front of this one
theyre all inactive tthough i believe, i'll have a double check though
Back from eating, any advice for the code I have?
what does it mean if my cursor has a little lock on it?
not sure what you mean by that
still nothing, could it be to do with the fact im using the new input system? im using both for active input handling
no, you have the correct input module
so it's fine
to be clear, im currently trying to click on this gun image, which has the drag drop script, and it has thiis script
oh wait
Is there a way to get the height of an canvas image in world units without me doing my own screen calculation.
i think the debug for comments was disabled 💀 @leaden ice
it was working this whole time
i didnt see that LMAO sorry
thanks for your help though
Would anything in my physics do something with it?
How can I request to not Burst compile some methods in a job?
[BurstCompile]
private struct MyJob : IJob
{
// Not Burst this
public void Execute()
{
ManagedCode();
UnamangedCode();
}
// Not Burst this
void ManagedCode() {}
[BurstCompile]
void UnamangedCode() {}
}
I think that should work
On IJob and IJobParallel you have to put [BurstCompile] on Execute as well for it to be burst compiled
nope
nope
nope
do not fall for that trap
it doesnt work like that
Lol
[BurstDiscard] literally means the code wont be compiled when burst is on
Oof
Not sure you can get method level granularity with it
It's at the job level right?
Hi, should I grab input always in Update, or is FixedUpdate fine? Assuming I'm using Input.GetAxis (no GetKeyDown etc.)
damn the docs really do not make that clear
dw, i fell for it too. The paragraph in the example explains it properly
Always Update is best practice but if it's continuous input it will technically work ok in FixedUpdate
The idea is that Update is the exact cadence that input data updates so you will be reading it exactly when it may change. No more no less.
It doesn't work. I already tried and got surprised to discover that it "deletes" the method
What's your goal? Why do you want to disable burst for the method
Are you trying to access managed objects or something?
Half the job uses managed code, half the job doesn't, my goal was:
void Execute(int index, TransformAccess transform)
{
Managed1(...);
Unmanaged1(...);
Managed2(...);
Unamanaged2(...);
Managed3(...);
}
And apply BurstCompile to the unmanaged ones.
I'm using a character controller for my player. I noticed that when platforms collide with the player, they don't always push it. If the player is standing completely still, the platforms will pass right through it. Does anyone know how to fix this?
you can't use managed objects in a job no matter what
I can
you technically can through statics (not that doing that is recommended as it avoids the safety system)
It works, but the Burst fail
you just can't pass them into the struct
Exactly, or by pinning objects
In my code, since this is a global manager, I just used static to get the managed data
what you put above should work (as the execute isnt [BurstCompile])
whats the error?
maybe you need to separate this into two jobs one that uses managed objects and one that doesn't.
No, the compiler tries to Burst the Execute, which fails:
Burst error BC1042: The managed class type `NavigationAgent[]` is not supported. Loading from a non-readonly static field `NavigationAgentManager.agents` is not supported
It would be 5, and I was using that before... but I noticed that scheduling 5 jobs per frame was quite expensive... so I wanted to reduce it to 1
can you just stick your code in a paste site
!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.
just before I go and open Unity and try doing it myself
I can't brain this morning. I want this gel ball to bounce around at a constant speed, but ... it's not. Any ideas?
private IEnumerator GelFloatCoroutine()
{
Vector2 endPos = GetNextGelLocation();
float _duration = Mathf.Abs(((Vector2)transform.position - endPos).magnitude / 800f);
_currentTween = transform.DOLocalMove(endPos, _duration).SetEase(Ease.Linear);
yield return _currentTween.Play().WaitForCompletion();
transform.localPosition = endPos;
DoNextAnimation();
}
GetNextGelLocation() gets a Vector2 along the edge of the screen
oh!
.position and not .localPosition
🤦♂️
huh sorry, i think i might be just misremembering it
I guess Execute is always burst compiled with that attribute
I guess the way to get around it is to have the logic in a separate class
I am heartbroken to discover that those are worldPosition. Is there an easy way to make a rigidbody be constrained in localPosition?
Why they made that??
Yep, sadly
not built in, no
:c thanks
Ok, thanks
BTW, it's me or if I apply BurstCompile to a method, it will "propagate" that attribute to any method that it calls (i.e: it will also Burst compile them)?
yup, thats how it works
Interesting
so if you have any downstream managed stuff then you can't use burst
Ok
The line 108 throws a StackOverflowException. _replayBuffer is a Queue and this method is called up to 60 times a second. How do I avoid the StackOverflowException and why does it happen?
Is there any reverse P/invoke or stuff that I can use to call managed code from Burst?
Just wondering
gotta admit i've never tried
A StackOverflowException usually indicates unbounded recursion. A good first step to investiaget would be to look at the full reported stack trace in the error message
public void SetPlayerStats()
{
int hp = 500;
int atk = 100;
foreach (var item in EquippedList.Values)
{
if(item !=null)
{
hp += item.hp;
atk += item.atk;
}
}
GameManager.instance.player.SetStats(hp, atk);
}```
Having this called in constructor of class throws errors...however having it set in another class like this doesnt...any ideas why?
playerInventory = new();
ExampleInvAdd();
playerInventory.SetPlayerStats();
Hello
well there's obviously some race condition then
which part in this is null GameManager.instance.player?
nope
is this object a MonoBehaviour? You cannot create MonoBehaviours with new().
something hasnt been set up in time
Also share the error(s)
neither is GameManager.instance.player.stats
¯_(ツ)_/¯
playerstats are setup in awake
NullReferenceException: Object reference not set to an instance of an object
PlayerInventory.SetPlayerStats () (at Assets/Scripts/Inventory/PlayerInventory.cs:212)
PlayerInventory..ctor () (at Assets/Scripts/Inventory/PlayerInventory.cs:31)
UnityEngine.Resources:Load(String)
BootStrapper:Execute() (at Assets/Scripts/DontDestroy/BootStrapper.cs:6)
NullReferenceException: Object reference not set to an instance of an object
PlayerInventory.SetPlayerStats () (at Assets/Scripts/Inventory/PlayerInventory.cs:212)
PlayerInventory..ctor () (at Assets/Scripts/Inventory/PlayerInventory.cs:31)
UnityEngine.Object:Instantiate(Object)
BootStrapper:Execute() (at Assets/Scripts/DontDestroy/BootStrapper.cs:6)
well is the GameManager instance also set in awake?
yes
player is set publicly
So then which awake is running first?
aka drag in
inventory isn't created until start
Awake is before Start
public class GameManager : MonoBehaviour
{
public static GameManager instance;
public void Awake()
{
instance = this;
}
public void Start()
{
//could try 60 also for ex)
Application.targetFrameRate = Screen.currentResolution.refreshRate;
Scene a = new Scene();
LoadSceneMode b = new LoadSceneMode();
SceneManager.sceneLoaded += LoadState;
SceneManager.sceneLoaded += FindPlayer;
SceneManager.sceneLoaded += FindEnemies;
LoadState(a, b);
FindPlayer(a, b);
FindEnemies(a, b);
playerInventory = new();
ExampleInvAdd();
playerInventory.SetPlayerStats();
}```
Where does BootStrapper:Execute() run
public class Player : Fighter
{
float movement;
bool jump;
bool down;
protected TextMeshProUGUI hpText;
[SerializeField] Joystick joystick;
[SerializeField] Button jumpButton;
[SerializeField] int atk = 3;
[SerializeField] float atkspd = 1f;
[SerializeField] int multishot = 1;
[SerializeField] Transform head;
bool isMobile = false;
protected override void Awake()
{
base.Awake();
myJumps.maxJumps = 2;
stats.attackDmg = atk;
stats.attackSpeed = atkspd;
stats.multiShot = multishot;
}```
^?
using UnityEngine;
public static class BootStrapper
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Systems")));
}
Ok that's going to be before any of your Awakes
not quite sure how it would cause the issue still
What script(s) are on the Systems object
PlayerInventory?
Show this line? PlayerInventory.SetPlayerStats () (at Assets/Scripts/Inventory/PlayerInventory.cs:212)
kinda...playerinventory is created inside the gamemanager
oooh
I have it created in another spot also
GameManager.instance.player.SetStats(hp, atk);
what Im finding says GameManager is null
yeah looks like PlayerInventory.Awake is running before GameManager.Awake
how could that happen if the only instance its created is inside GameManager?
I don't see any instance being created in GameManager. Are you talking about this?
playerInventory = new();
that's a giant red flag anyway
you cannot create MonoBehaviours with new
it isn't a monobehavior
just a regular ol class
public class PlayerInventory
{
public List<Items> ArmorList { get; private set; }
public List<Items> WeaponList { get; private set; }
public List<Items> JewelryList { get; private set; }
//Helmet, Armor, Weapon, Jewelry
public Dictionary<ItemType, Items> EquippedList { get; private set; }
int gold;
int gems;
int xp;
public PlayerInventory()
{
ArmorList = new();
WeaponList = new();
JewelryList = new();
EquippedList = new()
{
{ ItemType.Armor, null },
{ ItemType.Weapon, null },
{ ItemType.Jewelry, null },
{ ItemType.Undefined, null }
};
SetPlayerStats();
}
gotcha. Looks like there's one being created in GameHandler too?
commented it all out
using UnityEngine;
using System.IO;
using Assets.HeroEditor.Common.Scripts.CharacterScripts;
using Newtonsoft.Json;
public class GameHandler : MonoBehaviour
{
string path;
string json;
public Character character;
void Start()
{
//path = UnityEngine.Application.persistentDataPath + "/Inventory.json";
//SaveInv();
//LoadInv();
}
public void SaveInv()
{
PlayerInventory test = new();
//json = JsonUtility.ToJson(test);
json = JsonConvert.SerializeObject(test);
Debug.Log(json);
//Debug.Log(test.bag.Count);
//Debug.Log(test.equipped.Count);
File.WriteAllText(path, json);
}
public void LoadInv()
{
json = File.ReadAllText(path);
//Debug.Log(json);
PlayerInventory test = JsonUtility.FromJson<PlayerInventory>(json);
test.EquipOnLoad();
}
}
so it should only be created/happening inside gamemanager
(and shopEquipment which is in the scene)
where do you assign GameManager.player?
public void SetPlayerStats()
{
int hp = 500;
int atk = 100;
foreach (var item in EquippedList.Values)
{
if(item !=null)
{
hp += item.hp;
atk += item.atk;
}
}
if (GameManager.instance == null)
Debug.Log("GameManager is null");
if (GameManager.instance.player == null)
Debug.Log("player is null");
if (GameManager.instance.player.stats == null)
Debug.Log("stats is null");
GameManager.instance.player.SetStats(hp, atk);
}
it throws error saying the GameManager.instance ==null
ok good
public class GameManager : MonoBehaviour
{
public static GameManager instance;
public void Awake()
{
instance = this;
}
public void Start()
{
//could try 60 also for ex)
Application.targetFrameRate = Screen.currentResolution.refreshRate;
Scene a = new Scene();
LoadSceneMode b = new LoadSceneMode();
SceneManager.sceneLoaded += LoadState;
SceneManager.sceneLoaded += FindPlayer;
SceneManager.sceneLoaded += FindEnemies;
LoadState(a, b);
FindPlayer(a, b);
FindEnemies(a, b);
playerInventory = new();
ExampleInvAdd();
playerInventory.SetPlayerStats();
}
if I have it called SetPlayerStats() here it works...if I have the SetPlayerStats() inside constructor it breaks
¯_(ツ)_/¯
disabled ExampleInvAdd() and it still works...thus nothing inside that should be helping "fix" it
the thing is
look at this stack trace
GameManager.Start is not involved
Did PlayerInventory used to be a MonoBehaviour at some point in the past or something?
Somehow Resources.Load is directly calling the constructor 🤔
not sure, it may have been at some point
GameManager has a public PlayerInventory playerInventory;
I wonder if your prefab doesn't have an orphan copy of the script on it still or something
oh right
this will do it
if its serialized
but I don't have a =new() on it?
can you try making that [NonSerialized] for a minute
[NonSerialized] public PlayerInventory playerInventory;```
see if that changes anything
that indeed does fix it thanks!
didn't realize if I just had it public it would auto-create a new()
Unity's serialization creates "empty" objects for all serialized fields
good to know that [NonSerialized] is a thing to thanks!
Hi, when I set rigidbody.centerOfMass=Vector3.zero, all child gameobjects with rigidbodies stop moving when the parent object moves - can this be remedied somehow? I need the centerOfMass to be zero, because otherwise when I rotate the parent object, the child objects are involved in calculating the center of rotation, which is not something I want
Are the child Rigidbodies dynamic?
Why do you have child rigidbodies?
Typically you have one Rigidbody parent and then just colliders as the children
I have a big object, and small objects moving around on its surface
big object moves, small objects also move, but I don't want the big object to leave them behind
I would use two physics scenes for this
assuming you want the small objects on the surface to treat the big object as their entire world
not exactly - the small objects need to interact with objects outside of the big object, random completely unrelated ones
Sounds pretty complex 😵💫 that could be done with proxy objects in the "internal" physics scene though
your solution sounds complex 😵💫
but well, alright, I'll check out the physics scenes, never heard about them
Your game sounds complex 😜
I think you're going to end up with complexity either way here
Hello, was wondering if anyone knew how to stop colliders from going through walls? Maybe cutting them off if that's even possible or somehow making sure if a player is directly in front of the collider but behind the wall anyone know any good tutorials for this or know how I would go about approaching this??
you could use raycasts?
or boxcasts
(non-trigger) colliders won't go through walls as long as you move the object in a physics-friendly way
ie. using a Rigidbody
Use a raycast as a secondary check when you detect a trigger to make sure it's in line of sight too
I assume this is for some kind of cone of vision kind of thing?
actually yeah a raycast is something i didnt think about that
and yes this is for a cone of vision
oh okay however i need it to not collide with other objects
So they'll go through walls
Can't have both at the same time
oh yeah layering that also sounds like it
yes
How to get the forward vector of object in local space?
transform.forward
In local space?
Forward is always Vector3.forward in local space
in world space it's transform.forward
and in local space?
^
that's pretty much the definition of forward
what about?
Vector3.forward
this will always give you Vector3.forward back
aka (0, 0, 1)
barring floating point precision errors
https://cdn.discordapp.com/attachments/473801217869348889/1082775365841326111/2023-03-07_22-21-51.mp4
ummm how to fix this?
I'm using a rb.velocity to change player's positon
- This script to move on slopes
Anyone know how to return if a section of a texture is masked or not? I'm using a raycast & renderer.material.GetTexture("_MaskTexture"), but I'm not sure how to differentiate if the raycast is hitting the masked area or not.
what kind of mask are we talking about?>
It's a texture 2D asset input into my material shader, it adapts based on gameplay to create "painted" floors similar to splatoon.
So it's just one of the textures in your material? You'd have to read the texture at the UV where your ray hit and check what color the mask texture is at that point
See the code example here it's kind of close to what you want
https://docs.unity3d.com/ScriptReference/RaycastHit-textureCoord.html
This one writes to the texture, you just want to read.
In fact if you're doing a Splatoon thing you should be somewhat familiar with these techniques already
What would you call stats more generically? Like math wise even. Like I am thinking something like compoundable or something. You have your base value, and then modifier values on that(like adding specific value, multiplying by specific values).
stats
I find it is a pattern I use other places more generically, but I can't think of something to call it more generically then stats.
Statistics
EntityStatistics
AugmentableValue
ModifiableValue
ModifiableStat
I always think of Statistics as more finding logic/patterns in math, not the modification of numbers/values.
AugmentableValue like that one
Someone understood the assignment 😂
ModifiableValue is what I use in my current project for a thing that has:
- base value
- additive modifiers
- multiplicative modifiers
- replacement modifiers
Much appreciated, this is a great reference for getting the UV position! For next steps I'll try to focus this specifically to the mask, and see what values I can get back with GetPixel
I just have a class called BaseStat
I guess stats comes from dice times, where the outcome of actions is based on the likelyhood and combined values. Where in games it has more a meaning of just combined values.
Example: Your character has a statistically low chance of making that move work.
your stat, as it were, is too low
DnD was always presented as ability scores, but lately people refer them as character stats
A statistic (or stat) in role-playing games is a piece of data that represents a particular aspect of a fictional character. That piece of data is usually a (unitless) integer or, in some cases, a set of dice.
For some types of statistics, this value may be accompanied with a descriptive adjective, sometimes called a specialisation or aspect, th...
"There is no standard nomenclature for statistics; for example, both GURPS and the Storytelling System refer to their statistics as "traits", even though they are treated as attributes and skills."
I guess over all it is like the meaning for numbers in relation to an rpg, which does align with what I think of for statistics, but specifically what games call a stat would be attributes with modifiers mathmatically speaking.
"Bonus or base value"
Modifier makes more sense then Bonus, as I wouldn't consider a negative increase a bonus logically.
I'm trying to make a particle system (2d) that will generate particles from a point (bottom center) and have them fill the attached sprite. How should I go about doing this? Shape (Sprite) or ParticleForceFields seem like they could somehow be involved in this, but I don't know how
Question, when using the NavMeshSurface, is possible possible to choose some layers to carve the nav mesh but not add? I.e: I want obstacles and walls to carve the nav mesh, but I don't want to have a nav mesh on top of a large box.
Using RealtimeCSG, I created a massive bounding box about 1 cubic kilometer in volume, with walls about 1m thick, to act as an "out of bounds" area, which would cause projectiles to disappear and players to die/teleport upon touching it, so that nothing deviates infinitely from the level.
However it seems many of my projectiles phase through this box, meaning they won't disappear at all. Is there anything I can do to improve this collision system?
- Make the walls thicker
- reduce your fixed timestep
- reduce your projectile speed
- increase your projectile collider size
- Use a simple BoxCollider instead and use OnTriggerExit to destroy the bullets
- Make the walls thicker
Alright, good... that was an idea I had... 🤔
- reduce your fixed timestep
What do you mean?
- reduce your projectile speed
No can do.
- increase your projectile collider size
I may consider this. 🤔
- Use a simple BoxCollider instead and use OnTriggerExit to destroy the bullets
ABoxColliderfor what, exactly? The projectiles?
Also, I've been using OnTriggerEnter, so I'll try that. 🤔
- A BoxCollider for the 1KM box
It will accommodate for the massive void in the middle, right?
there is no void
the idea with a box collider is they will always be overlapping until they are NOT
There is in my box.
...
🤔
Huh.
So what you mean is have 'em always detect being within a big box, and when they're not in that box, they get despawned. 🤔
As for fixed timestep I mean this:
reducing it will mean physics simulation runs more frequently at smaller intervals of time
yes
in what context
Because it seems some of the generated meshes do adopt the necessary layer, but not the necessary tag.
Which means CompareTag may not be useful. 🤔
I'm not sure I follow this conversation anymore
🤔
If you're trying to limit the OnTriggerExit to certain layers, you should use the layer based collision matrix in physics settings
Ok, so what I attempted to do with OnTrigger[Enter/Exit] was to see if it was in contact (or not) with a GameObject with the "Out Of Bounds" tag.
you're overthinking this. also, this is buggy
you can do this still - or use layer based collisions to prevent other interactions
if you need a bounding box, create a game object with 6 box colliders
do not try to use a mesh with a void in the middle as a physics mesh
it is physically invalid
does that make sense @swift falcon ?
you cannot use a mesh generated this way with realtimecsg (which i am familiar with) for the purpose you want
period full stop
So, bounding box ought to be a simple set of box colliders.
that's correct
Ok.
you can emit particles from a texture
I love you guys
use a pyramidal shape
What you mean?
I don't want to create the particles in the shape of the texture, I want the particles to move so they fill the texture.
There may be a way to use emission from texture to work, but it creates a weird effect I'm not a fan of right now
well that's tricky now isn't it
maybe ask vfx and particles
We don't want to alter the shape of our obstacles and stuff
tough cookie. try to be creative with the differences between what is marked navigation static and what is not
you can use different geometry for navigation than for rendering
you can also specify navigation area as non-navigable i believe
lots of easy fixes
read the docs
But then how can I specify an entire layer to be of an specific area?
the general technique to get particles to move in a certain designed path is called... something about vector flow that i am still looking up
don't remember exactly
you can't. you can mark the objects as the docs show you
use the docs
That doc is about the old workflow.
I'm using the component based workflow...
I know I could add NavMeshModifier to each obstacle. But I wanted to know if there was a simple solution layer-wide.
i think you add navmeshmodifier to each obstacle
Ok
https://www.youtube.com/watch?v=Mh-zh_Hj0V4 vector fields*
This is a tutorial on using the Vector Field Asset for Unity which creates a vector field (aka 3D Texture) which can be used in the Visual Graph or in the Particle System Force Fields to apply force to the particles based on each pixel of the texture
Checkout my assets for more Tuts!
------------------------------------------------------------...
any ideas on how to increase randomness i have the following ```c
agent.transform.localPosition = new Vector3(Random.Range(-2f, 2f), 4f, Random.Range(-2f, 2f));
Random.InitState((int)System.DateTime.Now.Ticks * 123);
block.transform.localPosition = new Vector3(Random.Range(-2f, 2f), 4f, Random.Range(-2f, 2f));
Random.InitState((int)System.DateTime.Now.Ticks * 321);
goal.transform.localPosition = new Vector3(Random.Range(-2f, 2f), 3, Random.Range(-2f, 2f));
but this seams to keep them relativly together
also only spawns in the top half of the parent
Why are you setting the state of Random manually?
There's no need for that
Unless you're doing some kind of seeded deterministic thing
no I am not I just read that that can help
Also casting Ticks to an int is going to end up truncating probably
So you're likely setting the seed identically in both those calls
Hence non randomness
They're spawning at the top because you're using constant y positions, no?
by top half I mean from a birds eye sorry for the confusion
as you can see the objects spawn close to each other especially the blue and the green(in this case)
well you're only spawning within this -2, 2 range
that's not very far
And depending on the scale of the parent object it may be even smaller
I was under the impression that -2f , 2f was the range of the parent?
when I set it to -10f 10f (the size of the parent) it always spawns out side
I don't know what to say
it's just a random position between -2 and 2
it has nothing inherently to do with the size of the parent
(other than being affected by its scale, since it's local position)
oh 🤦♂️
if the parent is 10x10 then you'd do -5 to 5
Anybody tell me why i have to hit the spacebar multiple times before i actually jump
`using UnityEngine;
namespace Com.HighFiveGamesStudio.GetYoGuns
{
public class Motion : MonoBehaviour
{
//Variables
public float speed;
public float sprintModifier;
public float jumpForce;
public Camera normalCam;
private Rigidbody rig;
private float baseFOV;
private float sprintFOVModifier = 1.5f;
private void Start()
{
Camera.main.enabled = false;
baseFOV = normalCam.fieldOfView;
rig = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
//Axles
float t_hmove = -Input.GetAxisRaw("Horizontal");
float t_vmove = Input.GetAxisRaw("Vertical");
//Controls
bool sprint = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
bool jump = Input.GetKeyDown(KeyCode.Space);
//States
bool isJumping = jump;
bool isSprinting = sprint && t_vmove > 0;
//Jumping
if (isJumping)
{
rig.AddForce(Vector3.up * jumpForce);
}
//Movement
Vector3 t_direction = new Vector3(t_vmove, 0, t_hmove);
t_direction.Normalize();
`
`float t_adjustedSpeed = speed;
if (isSprinting)
{
t_adjustedSpeed *= sprintModifier;
}
Vector3 t_targetVelocity = transform.TransformDirection(t_direction) * t_adjustedSpeed * Time.deltaTime;
t_targetVelocity.y = rig.velocity.y;
rig.velocity = t_targetVelocity;
//FOV
if (isSprinting)
{
normalCam.fieldOfView = Mathf.Lerp(normalCam.fieldOfView, baseFOV * sprintFOVModifier, Time.deltaTime * 8f);
} else
{
normalCam.fieldOfView = Mathf.Lerp(normalCam.fieldOfView, baseFOV, Time.deltaTime * 8f);
}
}
}
}`
I set it to -5,5 and the objects spawn outside pretty often
because you're trying to read input in FIxedUpdate. You should only read input in Update
Ok, thanks
man I feel like I could spend a lifetime learning this engine and still barely understand it
I've been studying it like CRAZY for over 3 years and I still see shit I've NEVER seen before to this day
any sufficiently complex piece of software is like this
I guess, but you'd figure it'd slow down eventually
I haven't even touched any of the DOTS stuff yet. And that's probably a huge rabbit hole
Does scaling a game object also scale any colliders attach to it and its children?
yes
Note there are some caveats to that when it comes to colliders. SphereCollider is always a sphere, even if you try to "skew" it with a weird scale. Similar restriction on CapsuleCollider
Does it expand to the largest of the coordinates?
something like that. I don't remember exactly
k
maybe the smallest, maybe the largest 😉
lol
Realistically, how much of an impact of performance do public references have? I've always been taught that avoiding unnecessary public references is good practice, but if my game is having performance issues how likely is it that they're the cause?
approximately 0%
Use the profiler to diagnose your performance issues
What's that?
the tool designed to diagnose performance issues
Alright better question, where's that
google is a thing you will need to use a lot if you have any hope of creating a game
Avoiding public references is good practice, but not for performance reasons.
What reasons, then?
Good code.
classes that interact with a bunch of other classes is a mess to code, debug, everything
Readability, extendability, debuggability.
but you'll write trash code in the beginning no matter what which is to be expected
you have to understand what's wrong with bad code by writing some before you can understand how to avoid/fix it
people can tell you it's bad all they want but until you understand it from personal experience I doubt it'll really do anything
just my two cents
Hmm, looking for some help if anyone can provide a bit of feedback! Context: moving rigidbodies while simultaneously applying velocity (moving platforms, but learning what's wrong will help me with a lot I'm sure)
Currently my character controller is a rigidbody2d controller that adds force to the player in fixedupdate depending on inputs.
The platform script is detecting rigidbodies on collision and then using transform.translate to move them (in lateupdate). It uses the platform's stored last position and current position to figure out what to do.
The problem currently is the platform causes visual jitter to everything riding on top of it, and there's definitely something wrong.
I mostly understand what's going on, but the specific details of the issue feel like I'm not quite grasping ahold of enough info to figure out what I need to change. If I had to take an educated guess I'd probably think it was related to a number of things including when I'm calculating/moving the RB, as well as potentially needing to lerp the values or something... A bit clueless though.
If anyone has resources to guides on the topic that are better than the random youtube info I keep stumbling into, and can point me in the right direction (or can tell me straight up what the problem is) I'd be grateful
this is a different approach I tried, using parenting the object (player in this case) to the platform on collision
it works a lot better, and seems to be fine, save for the issue of some persistent jitter I can't get rid of
see I'd heard not to before, and then every tutorial or post on a forum goes "translate it lol"
I feel insane
if you want your props to move with the platform you could potentially use joints or make it kinematic with parenting
translations completely avoid the physics engine so no collisions, shit can warp through walls etc
right,
so what would a best practice be for moving platforms carrying rigidbodies/the player
exerting additional forces?
I told you a few options
I'll need to look into joints. Making it kinematic doesn't sound like it will work for me though, since I'd want it to continue to function as a dynamic object
I'm not really sure though. I'm reaching a point where I wonder "Should I just code everything as kinematic?"
I'm trying to imagine what I'd need to change in the controller to accommodate a shift to kinematic
there
may not be issues, now that I think about it
thanks, it's something to think about for the moment

also are those meshes ? or are you just using 2D colliders
2d colliders, I'm rendering 3d meshes but the game is using 2d for everything
this way I can do funny things with lighting and animation
did you try only moving platform with Add.Force ?
ohh so the platform isn't rigidbody ?
correct
thats what I meant when i said kinematic
but that would require diff movement than addforce
I'm just generally confused now. So, did you mean change the player to kinematic to match the platform? Or did you originally mean make the platform kinematic
if I make the player kinematic at any point I've got to use some different method to move them, since force can't be applied to kinematic objects, correct?
is the player also a rigidbody ?
the player is an RB2D
dynamic objects for physics based interactions I wanted to be rigidbodies
oh ok , try only having platform move with addforce
alright
Not sure where to post this
But
What is the easiest way to set up player data recovery when using firebase firestore?
"player data recovery" is a vague and probably complicated subject
you'd have to explain exactly what that means in the context of your game
does anyone know what retail disks and gold master disks are? this is the steamworks sdk docs
it just kinda uses the terms like everyone knows what they mean, and I can't find anything about it anywhere
disks ? what is this 2007
I'm pretty confident they don't mean physical disks? but I don't know
not sure what else they would mean
nevermind. Maybe that's exactly what that means
"A final version of software ready for release to manufacturing"
this is the docs if you're curious
maybe I'm just stupid lol. Can't really figure it out
I think it's literally what I said lol
has to do with putting your game on disk and auto install from steam or something
i think
Is checking if( GameObject.GetComponent<T>() != null ) significantly more performance intensive than implementing a Tag system for type T and using that?
so like people with shite internet can still install your game without steam download
interesting
just a disk?
I didn't even know that was a thing
The Steamworks SDK includes a customizable installer that you can include on your gold master. The installer is designed to help users install Steam and begin loading your game as quickly as possible. The installer has also been designed to ensure compatibility with the installation portion of the Games for Windows certification.
like if you create special edition probably with art and shit
steamworks docs try not to be impenetrable challenge difficulty impossible
thanks king @potent sleet
Not sure what you mean by a tag system for type T
But get component is not that heavy.
I just mean using tags instead of GetComponent
it's always better to use types than strings imo
strings aren't type safe and very brittle @thin frigate
yeah it literally just works this way and idk why anyone ever was telling me to do it differently
if you're caching component references it shouldn't even matter
which way?
kinematic platform moved with force
noice
Get component might be slightly slower, as it probably needs to loop the list of components on the GO.
But the difference is probably negligible
Alright
I'm trying to optimize my code to deal with having even a handful of projectiles in the scene at once, and it's being difficult.
I always say bro optimize geometry and draw calls
ain't no way the fraction of a millisecond you save avoiding the lightning fast GetComponent calls are going to put a noticeable dent in anything
plus use the profiler anyway
This is a 2d Asteroids clone, I'm not sure how applicable that is here
then performance is a nonissue
also I don't want to be assed to wait 20 minutes for a build
It IS an issue, though, that's the issue.
what does the profiler say
It doesn't?
this call is unlikely to appear in your profiler
I don't even know if you CAN use the profiler in a build, it's in the engine
have you looked at corgi engine 2.5d?
Window -> Analysis -> Profiler
The implementation is inside of my collision checks, so this is being called for every single object in the scope.
what does the profiler say
This I guess
spend some time learning how to read the profiler
it's going to be much more useful figuring out where you're writing inefficient code that way then just guessing at optimizations that might not even do anything
it'll even show you how much memory different things are using. It's extremely useful
you probably want hierarchy view not timeline
look up tutorials
already on it
Looks neat, but most things I can implement seem easy enough to tackle myself. I've already solved slope movement, etc. My plans are pretty extensive, so it's probably best I handle it all myself.
Alright apparently around 85% of the performance was being taken up by drawing gizmos. not very cool.
there you go
I currently have players anonymously authenticating with firebase , then they can choose to link with facebook.. I save the players data on firestore naming the doc the players uid.. now if my player clears local data and gets back in to the game a new anonymous auth is created and when logging in to Facebook again it tries to re-link to the new account , I'm unable recall the players originally assigned uid.. I'm currently working on a solution by trying to save email and uid on realtime Database
Hrmm, if addforce works on kinematic objects.. addtorque should as well, right? in order to rotate it.
I just wanted to test rotating a kinematic platform in place.
given it's a 2d rigidbody, this should be all it takes, I believe
Forces shouldn't work on kinematic objects. Guessing you meant non-kinematic objects.
Yes you need to associate the email or Facebook account with your user account that's all
what's the term for the velocity equivalent for rotation? is there one?
Velocity doesn't work on kinematic objects either, unless you're in 2D
I am in 2d
I got it somewhat working but it seemes I have messed up something.. One minute I'll show what I've got vs what i want and show the script
Angular velocity
thanks, I coulda swore I tried that but my brain is fried

I am getting lags everytime I swap audio and AudioSource.Play() different musics, what are some good ways to reduce this?
Like what are the ideal settings for music, sound effects, etc?
Just preload and load in background enabled for all musics? Will that take a lot of memory?
this is what i get (the email will fill in when player signs in with facebook) ... See how it has double values both inside and outside the players document? then I need ti get tit to wokrk only when player logs in with facebook
my script
https://pastebin.com/y247szEe
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
this is what im looking for
Can someone show me how to post code in here? I've done it before so I know it needs to be done, but it's been so long I forgot the syntax.
sure, it's !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.
{
// Game Initializations
public TMP_Text moneyText;
int money = 5000;
// Main Game Start
void Start()
{
moneyText.text = "$" + money.ToString();
}```
My code runs but causes the play to pause and I have to unpause it each time.
I'm also getting this error message and not sure what I need to do here to resolve that. "NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () "
Show the entire console error
And under the Inspector, yes I have the TMP_Text linked to MoneyText
@dusk apex NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () (at Assets/Scripts/GameManager.cs:25)
Which line is 25?
This line in Start() moneyText.text = "$" + money.ToString();
Money text is null
I'm not sure how to resolve that
Make sure you've assigned it in the inspector
It's pausing because you have an error and you have error pause on. Fix your error
Thanks for that. Now I know
I made a List/Array and I wanted to reference all child gameObject in parent into the List/Array automatically by script I couldnt figure out how. Anyone got ideas?
without find tag if possible
What's a List/Array? It's either one or the other
Well its more to List
@dusk apex Would my code update the text, if it wasn't assigned under Inspector?
like List<GameObject> those stuff
An array would be like
GameObject[]
I've seen where this might be related to not have an instance, but it's a single player game and only one Money UI text field. Do I really need to do a search/find on the name of my TMP_Text?
uh yea I know cause they're almost the same thing except List is more flexible
so Im trying to figure this out
with list
You mean to make a variable reference
Make it public and drag and drop it in the inspector
Yes, It's like the game's score. My code works but is giving me NullReferenceException: Object reference not set to an instance of an object
GameManager.Start ()
Show the inspector.
Yeah the reference isn't comeplete
If it's not assigned, accessing the text property of the tmp component will throw an NRE.
You have a copy of the script in the scene with the reference left unassigned.
Make the variable public and drop the game object in to the slot
This is what is throwing me off because I have it assigned here underlined in red
Cool now show all the other copies in the scene
Do you mean all the TMP_Text?
Is it a child object? Does the parent get disabled on start?
hello
Debug.Log($"{name} has this script", gameObject);
I am newbie, which projects do you suggest me to learn unity? I can use c# and unity well.
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
My TMP_Text is a chid of Canvas->UI
Stop worrying about the text
@leaden ice I have completed unity learn 2d ruby game doc. It was awesome and I have learnt awesome things. Yet, I like to build something from scratch by my own self. What do you suggest me to build ?
Canvas and Canvas->UI->MoneyText are the only two things in my scene that call to GameManager at the moment
Make data recovery
Wdym "call to GameManager"?
Find all of them
You really should only have one
Fix any without a reference set
Or delete it if not needed
Sorry PreatorBlue but I'm not sure what you mean by having multiples
Did you try placing this log in your code?
In start preferably
@dusk apex Yes. I got just this
MoneyText has this script
UnityEngine.Debug:Log (object,UnityEngine.Object)
GameManager:Start () (at Assets/Scripts/GameManager.cs:26)
Did it print once only?
Correct
Are you sure it didn't print twice? Do you have Collapse enabled on your console window?
I'm sure, I just doubled checked for you
Maybe you have the script on that one object twice
Okay.. Take made me think of something. I did have it also listed under the parent Canvas object
I unticked it and error goes away
...
Try logging the value of the money text component cs Debug.Log($"{name}'s component for money text was : {(moneyText != null ? "Not Null" : "Null")}");
I'm still getting use to Unity, so it one script per object?
It's as many as you want but it needs to make sense
Anyway the log wasn't printing because you put it after the code with the error
Ah, so there were two.
Yes
Okay, so if I have more than two references to the same script in a scene I need to do the search/find?
He even said as much here
No
Irrelevant
The number doesn't matter
You have to assign your references that's all
im looking into doing pathfinding on a grid, but i need to find the nearest enemy on the grid while moving around allied units. can i use pathfinding to find the nearest enemy then actually follow that path?
Well my code hasn't change just the references
A*
Of course, why not?
i cant just find the nearest enemy in a range
Yes.
why not?
So what would be the Correct way if I had it with two references?
Use Breadth First Search to find the nearest enemy in range
i need to find the nearest enemy that is the fastest to get to
IDK what you mean. You just have to assign all your inspector references
You didn't assign one of them
Ah... that's making more sense now
Maybe you're mistaking the word references for instances
Yeah that second one is showing up but nothing is assigned so it's showing NULL
Ugh.. so dumb when you know what's going on
If you've got two instances in the scene, each instance must have their fields properly set before using their fields else you'll get NREs
I just updated this code to get it working tonight, so left out something PraetorBlue was right
does A* not work ?
A* is for pathfinding
Yep.. Thanks for that.. I thought I only had one until I went looking and saw what PraetorBlue was talking about.
To find the nearest enemy you would use Dijkstra's
When you drag something into the field, that field now references what's been dragged in via inspector.
can i ask A* to find the nearest enemy taking into account allies? then move to that enemy?
Sure
yeah thats what i thought
Now that I'm on this side of understanding the problem, it's a really basic and dumb mistake..
i need to search for the destination then pathfind to it
Dijkstra's algorithm will give you both the nearest enemy and the shortest path to that enemy
!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.
Breadth first search is basically Dijkstra's with the assumption that all edges in the graph are equally weighted, which is likely the case for a basic grid.
I see you took some inspiration from my code ? @long totem
I think I copy & past somewhere else months ago XD
Last time it worked fine
I just dont know how it stop working suddenly
what "stopped working"
it's always gray
That's not a button. Just a reference to the script asset
And I just noticed the classes are not green
you might need to configure your VS then
those under public class
we don't have much to go by here, show some code or anything relevant
Is there a length requirement for posting codes?
yes and, follow this to post code properly
!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.
so what happens when you run the code
It wont capture the the screenshot when I click "camerainfo"