Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to call function from other script but the game objects defined are not loaded.And gives error
NullReferenceException: Object reference not set to an instance of an object

My code..i am calling executemyoperation() function..It does calls but do not load the objects why?

C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEngine.ProBuilder.Experimental.CSG
{
    public class Subtractoperation : MonoBehaviour
    {

        public GameObject rodtomake;
        public GameObject tool;
        private Mesh result;
        GameObject composite;
        public void executemyoperation()
        {

            Debug.Log("do subtraction");
            result = CSG.Subtract(rodtomake, tool);

            composite = new GameObject();
            composite.AddComponent<MeshFilter>().sharedMesh = result;
            composite.AddComponent<MeshRenderer>().enabled = result;
            Destroy(rodtomake);
            Destroy(tool);
        }
    }

}


What I have tried:

I am calling this function as
C#
Subtractoperation d = new Subtractoperation();
d.executemyoperation();
Posted
Updated 18-Jul-22 20:06pm
v2

1 solution

Object reference not set to an instance of an object
 
This error happens when you try to use a property or call a method of an object that is null. More details: here[^]
 
A simple use of Visual studio DEBUGGER can tell you the object because of which it is happening. Just look at the stack trace and put a debugger on that line. Check the objects of that line and see if any one is null and you are trying to use that objects property. Handle the same.

Few things you should not miss assessing while debugging:
1. Value of rodtomake
2. Value of tool
3. Value of result
 
Share this answer
 
v2
Comments
Member 11391151 6-Aug-20 1:42am    
When i attach this function to a button it works fine but when i call it by script then error occurs
Sandeep Mewara 6-Aug-20 1:48am    
Still, DEBUG and see which object is null that is causing it. Try.
Member 11391151 6-Aug-20 2:04am    
OK i got it...Thanks! it was too simple...I simply assigned gameobjects through script and it worked.
Sandeep Mewara 6-Aug-20 2:50am    
Super! Good to know it is resolved.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900