why GetComponent returns null reference for imageEffect?

五迷三道 提交于 2021-02-05 08:16:46

问题


this problem is unsolvable or what?i don't need to provide any code example it just doesn't work to anyone!and i don't know how its possible,you just have to try this : GetComponent<DepthOfField>().enabled = false;

assume that we have a MainCamera object and we attach it a DepthOfField image effect Script.and we create another script named whatever and attach it to the MainCamera and in the whatever script we just call this:

void Start() {
  GetComponent<DepthOfField>().enabled = false;
}

shouldn't it work?well it doesn't, it returns null reference exception even if the script is attached to the main camera.is it fixable? and if yes i need it !


回答1:


It should work because they are both attached to the same GameObject. Although, there are many other ways you can try to fix this.

You can just do

 DepthOfField myDept;

void Start() {
myDept = GameObject.Find("MainCamera").GetComponent<DepthOfField>();
myDept.enabled = false;
}

Or You could make DepthOfField public then assign the DepthOfField from the Editor. For example,

public DepthOfField myDept; 

//Drag and Drop the MainCamera GameObject from the scene to this and it will automatically assign the DepthOfField script to the myDept.

Then you can do

myDept.enabled = false;

For this to work, DepthOfField must be attached to the MainCamera GameObject.



来源:https://stackoverflow.com/questions/30003776/why-getcomponent-returns-null-reference-for-imageeffect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!